﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.Services;
using System.Web.UI;
using System.Web.UI.WebControls;
using BLL.Utils;
using CrystalDecisions.CrystalReports.Engine;
using CrystalDecisions.Shared;
using DAL.DataSet;
using DAL.Entity;
using DAL.Persistencia;
using NewTierra.Reports;
using NewTierra.App_Code;

namespace NewTierra.Pages.Servicos
{
    public partial class ServicosConsulta : BasePage
    {
        //ViewState["IdSupplier"] -- Usado na tela de MServicoSozinho

        public static string displayFiltro;

        protected void Page_Load(object sender, EventArgs e)
        {
            //PopulaGridSubServAdicionados();

            if ((base.ObterPerfilLogado() == (int)PerfilUsuario.Financeiro) ||
            (base.ObterPerfilLogado() == (int)PerfilUsuario.Operacional))
            {
                btnNovoServico.Enabled = false;
                btnExcluirServico.Enabled = false;
                btnLimparServico.Enabled = false;
                btnGerarRelatorioServicoPopUp.Enabled = false;
                btnGerarRelatorioServicoPopUpTarifario.Enabled = false;
                btnSalvarTarifas.Enabled = false;
                btnNovaTemporadaSubServico.Enabled = false;
                btnTemporadasCadastradas.Enabled = false;
            }

            if (!IsPostBack)
            {
                PopularDrops();
                displayFiltro = "none";

                txtMarkUpRelatorioTarifario.Text = "0";

                HttpContext.Current.Session.Remove("IDsFiltroStatusServicos");
                HttpContext.Current.Session.Remove("IDsFiltroTipoServicos");
                HttpContext.Current.Session.Remove("IDsFiltroTipoCategServicos");
                HttpContext.Current.Session.Remove("IDsFiltroCidadeServico");

                //TabTarifas.Enabled = false;
            }
        }

        protected String BrancoNulo(string texto)
        {
            if (texto.Equals(""))
            {
                return null;
            }
            else
            {
                return texto;
            }

        }

        protected String BrancoZero(string texto)
        {
            if (texto.Equals(""))
            {
                return "0";
            }
            else
            {
                return texto;
            }
        }

        protected string NuloZero(string valor)
        {
            if (valor == null)
            {
                return "0";
            }
            else
            {
                return valor;
            }
        }


        #region Popular Drops

        protected void PopularDrops()
        {
            PopularDDTipoServicoFiltro();
            PopularDDTipoServicoCategFiltro();
            PopularDDStatusFiltro();
            PopularddlStatusServico();
            PopularddlTipo();
            PopularddlTipoCateg();
            PopularddlPais();
            PopularddlCidade();
            PopularDDCidadeFiltro();
            popularDropTipoServico();
            popularDropTipoServicoCateg();
            PopulaDropMercadoFiltroBase();
            PopulaDropBaseTarifariaFiltroBase();
            PopulaDropMoedaFiltroBase();
            popularDropTipoBaseFiltroBase();
            //popularDropTipoServico3();
            //popularDropItemSubServico();
            PopulaDropPaisReport();
            PopulaDropCidadeReport();
            PopulaDropCambioReport();
            PopulaDropMercadoReport();
            //PopulaDropMercadoReportTarifario();
            popularDropBaseTarifariaReport();

            PopulaDropPaisReportTarifario();
            PopulaDropCidadeReportTarifario();
            PopulaDropCambioReportTarifario();
            PopulaDropMercadoReportTarifario();
            popularDropBaseTarifariaReportTarifario();
            //pupularDropSupplierReport();
        }

        protected void PopularDDTipoServicoFiltro()
        {
            try
            {
                using (NewTierraEntities Con = new NewTierraEntities())
                {
                    DDTipoServicoFiltro.DataSource = Con.S_Servicos_Tipo.ToList();
                    DDTipoServicoFiltro.DataValueField = "Tipo_Id";
                    DDTipoServicoFiltro.DataTextField = "Tipo_Nome";
                    DDTipoServicoFiltro.DataBind();

                    DDTipoServicoFiltro.Items.Insert(0, new ListItem("Todos", "0"));
                }
            }
            catch (Exception ex)
            {
                System.Diagnostics.StackTrace trace = new System.Diagnostics.StackTrace(ex, true);
                Log.Save((trace.GetFrame(0).GetMethod().ReflectedType.FullName), ("Linha: " + trace.GetFrame(0).GetFileLineNumber()), ("Column: " + trace.GetFrame(0).GetFileColumnNumber()), ex.Message);

                lblMsgCadServicos.Text = ex.Message;
            }
        }

        protected void PopularDDTipoServicoCategFiltro()
        {
            try
            {
                using (NewTierraEntities Con = new NewTierraEntities())
                {
                    int IdTipoServico = Convert.ToInt32(DDTipoServicoFiltro.SelectedValue);
                    ddlTipoServicoCategFiltro.DataSource = Con.S_Servicos_Tipo_Categ.Where(s => s.Tipo_Id == IdTipoServico).ToList();
                    ddlTipoServicoCategFiltro.DataValueField = "Tipo_categ_id";
                    ddlTipoServicoCategFiltro.DataTextField = "Tipo_categ_nome";
                    ddlTipoServicoCategFiltro.DataBind();

                    ddlTipoServicoCategFiltro.Items.Insert(0, new ListItem("Todos", "0"));
                }
            }
            catch (Exception ex)
            {
                System.Diagnostics.StackTrace trace = new System.Diagnostics.StackTrace(ex, true);
                Log.Save((trace.GetFrame(0).GetMethod().ReflectedType.FullName), ("Linha: " + trace.GetFrame(0).GetFileLineNumber()), ("Column: " + trace.GetFrame(0).GetFileColumnNumber()), ex.Message);

                lblMsgCadServicos.Text = ex.Message;
            }
        }

        protected void PopularDDStatusFiltro()
        {
            try
            {
                using (NewTierraEntities Con = new NewTierraEntities())
                {
                    DDStatusFiltro.DataSource = Con.S_Status.ToList();
                    DDStatusFiltro.DataValueField = "STATUS_id";
                    DDStatusFiltro.DataTextField = "STATUS_nome";
                    DDStatusFiltro.DataBind();

                    DDStatusFiltro.Items.Insert(0, new ListItem("Todos", "0"));
                }
            }
            catch (Exception ex)
            {
                System.Diagnostics.StackTrace trace = new System.Diagnostics.StackTrace(ex, true);
                Log.Save((trace.GetFrame(0).GetMethod().ReflectedType.FullName), ("Linha: " + trace.GetFrame(0).GetFileLineNumber()), ("Column: " + trace.GetFrame(0).GetFileColumnNumber()), ex.Message);

                lblMsgCadServicos.Text = ex.Message;
            }
        }

        protected void PopularDDCidadeFiltro()
        {
            try
            {
                using (NewTierraEntities Con = new NewTierraEntities())
                {
                    ddlCidadeServicoFiltro.DataSource = Con.Cidades.OrderBy(c => c.CID_nome).ToList();
                    ddlCidadeServicoFiltro.DataValueField = "CID_Id";
                    ddlCidadeServicoFiltro.DataTextField = "CID_nome";
                    ddlCidadeServicoFiltro.DataBind();

                    ddlCidadeServicoFiltro.Items.Insert(0, new ListItem("Todas", "0"));
                }
            }
            catch (Exception ex)
            {
                System.Diagnostics.StackTrace trace = new System.Diagnostics.StackTrace(ex, true);
                Log.Save((trace.GetFrame(0).GetMethod().ReflectedType.FullName), ("Linha: " + trace.GetFrame(0).GetFileLineNumber()), ("Column: " + trace.GetFrame(0).GetFileColumnNumber()), ex.Message);

                lblMsgCadServicos.Text = ex.Message;
            }
        }

        protected void PopularddlStatusServico()
        {
            try
            {
                using (NewTierraEntities Con = new NewTierraEntities())
                {
                    ddlStatusServicos.DataSource = Con.S_Status.ToList();
                    ddlStatusServicos.DataValueField = "STATUS_id";
                    ddlStatusServicos.DataTextField = "STATUS_nome";
                    ddlStatusServicos.DataBind();
                }
            }
            catch (Exception ex)
            {
                System.Diagnostics.StackTrace trace = new System.Diagnostics.StackTrace(ex, true);
                Log.Save((trace.GetFrame(0).GetMethod().ReflectedType.FullName), ("Linha: " + trace.GetFrame(0).GetFileLineNumber()), ("Column: " + trace.GetFrame(0).GetFileColumnNumber()), ex.Message);

                lblMsgCadServicos.Text = ex.Message;
            }
        }

        protected void PopularddlTipo()
        {
            try
            {
                using (NewTierraEntities Con = new NewTierraEntities())
                {
                    ddlTipoServico.DataSource = Con.S_Servicos_Tipo.ToList();
                    ddlTipoServico.DataValueField = "Tipo_Id";
                    ddlTipoServico.DataTextField = "Tipo_Nome";
                    ddlTipoServico.DataBind();

                    ddlTipoServico.Items.Insert(0, new ListItem("Selecione", "0"));
                }
            }
            catch (Exception ex)
            {
                System.Diagnostics.StackTrace trace = new System.Diagnostics.StackTrace(ex, true);
                Log.Save((trace.GetFrame(0).GetMethod().ReflectedType.FullName), ("Linha: " + trace.GetFrame(0).GetFileLineNumber()), ("Column: " + trace.GetFrame(0).GetFileColumnNumber()), ex.Message);

                lblMsgCadServicos.Text = ex.Message;
            }
        }

        protected void ddlTipoServico_SelectedIndexChanged(object sender, EventArgs e)
        {
            PopularddlTipoCateg();
        }

        protected void PopularddlTipoCateg()
        {
            try
            {
                using (NewTierraEntities Con = new NewTierraEntities())
                {
                    int IdTipoServico = Convert.ToInt32(ddlTipoServico.SelectedValue);
                    ddlTipoServicoCateg.DataSource = Con.S_Servicos_Tipo_Categ.Where(s => s.Tipo_Id == IdTipoServico).ToList();
                    ddlTipoServicoCateg.DataValueField = "Tipo_categ_id";
                    ddlTipoServicoCateg.DataTextField = "Tipo_categ_nome";
                    ddlTipoServicoCateg.DataBind();

                    ddlTipoServicoCateg.Items.Insert(0, new ListItem("Selecione", "0"));
                }
            }
            catch (Exception ex)
            {
                System.Diagnostics.StackTrace trace = new System.Diagnostics.StackTrace(ex, true);
                Log.Save((trace.GetFrame(0).GetMethod().ReflectedType.FullName), ("Linha: " + trace.GetFrame(0).GetFileLineNumber()), ("Column: " + trace.GetFrame(0).GetFileColumnNumber()), ex.Message);

                lblMsgCadServicos.Text = ex.Message;
            }
        }

        protected void PopularddlPais()
        {
            try
            {
                using (NewTierraEntities Con = new NewTierraEntities())
                {
                    ddlPaisServicos.DataSource = Con.Pais.ToList();
                    ddlPaisServicos.DataValueField = "PAIS_id";
                    ddlPaisServicos.DataTextField = "PAIS_nome";
                    ddlPaisServicos.DataBind();
                }
            }
            catch (Exception ex)
            {
                System.Diagnostics.StackTrace trace = new System.Diagnostics.StackTrace(ex, true);
                Log.Save((trace.GetFrame(0).GetMethod().ReflectedType.FullName), ("Linha: " + trace.GetFrame(0).GetFileLineNumber()), ("Column: " + trace.GetFrame(0).GetFileColumnNumber()), ex.Message);

                lblMsgCadServicos.Text = ex.Message;
            }
        }

        protected void ddlPaisServicos_SelectedIndexChanged(object sender, EventArgs e)
        {
            PopularddlCidade();
        }

        protected void PopularddlCidade()
        {
            try
            {
                using (NewTierraEntities Con = new NewTierraEntities())
                {
                    int IdPais = Convert.ToInt32(ddlPaisServicos.SelectedValue);
                    ddlCidadeServicos.DataSource = Con.Cidades.Where(c => c.PAIS_id == IdPais).OrderBy(c => c.CID_nome).ToList();
                    ddlCidadeServicos.DataValueField = "CID_id";
                    ddlCidadeServicos.DataTextField = "CID_nome";
                    ddlCidadeServicos.DataBind();

                    ddlCidadeServicos.Items.Insert(0, new ListItem("Selecione", "0"));
                }
            }
            catch (Exception ex)
            {
                System.Diagnostics.StackTrace trace = new System.Diagnostics.StackTrace(ex, true);
                Log.Save((trace.GetFrame(0).GetMethod().ReflectedType.FullName), ("Linha: " + trace.GetFrame(0).GetFileLineNumber()), ("Column: " + trace.GetFrame(0).GetFileColumnNumber()), ex.Message);

                lblMsgCadServicos.Text = ex.Message;
            }
        }

        protected void popularDropTipoServico()
        {
            try
            {
                using (NewTierraEntities Con = new NewTierraEntities())
                {
                    ddlTipoServico2.DataSource = Con.S_Servicos_Tipo.ToList();
                    ddlTipoServico2.DataTextField = "Tipo_Nome";
                    ddlTipoServico2.DataValueField = "Tipo_Id";
                    ddlTipoServico2.DataBind();

                    ddlTipoServico2.Items.Insert(0, new ListItem("Selecione...", "0"));
                }
            }
            catch (Exception ex)
            {
                System.Diagnostics.StackTrace trace = new System.Diagnostics.StackTrace(ex, true);
                Log.Save((trace.GetFrame(0).GetMethod().ReflectedType.FullName), ("Linha: " + trace.GetFrame(0).GetFileLineNumber()), ("Column: " + trace.GetFrame(0).GetFileColumnNumber()), ex.Message);

                lblMsgCadMServicos.Text = ex.Message;
            }
        }

        protected void ddlTipoServico2_SelectedIndexChanged(object sender, EventArgs e)
        {
            popularDropTipoServicoCateg();
        }

        protected void popularDropTipoServicoCateg()
        {
            try
            {
                using (NewTierraEntities Con = new NewTierraEntities())
                {
                    int IdServico = Convert.ToInt32(ddlTipoServico2.SelectedValue);
                    ddlTipoServicoCateg2.DataSource = Con.S_Servicos_Tipo_Categ.Where(t => t.Tipo_Id == IdServico).OrderBy(t => t.Tipo_categ_nome).ToList();
                    ddlTipoServicoCateg2.DataTextField = "Tipo_categ_nome";
                    ddlTipoServicoCateg2.DataValueField = "Tipo_categ_id";
                    ddlTipoServicoCateg2.DataBind();

                    ddlTipoServicoCateg2.Items.Insert(0, new ListItem("Selecione...", "0"));
                }
            }
            catch (Exception ex)
            {
                System.Diagnostics.StackTrace trace = new System.Diagnostics.StackTrace(ex, true);
                Log.Save((trace.GetFrame(0).GetMethod().ReflectedType.FullName), ("Linha: " + trace.GetFrame(0).GetFileLineNumber()), ("Column: " + trace.GetFrame(0).GetFileColumnNumber()), ex.Message);

                lblMsgCadMServicos.Text = ex.Message;
            }
        }

        protected void PopulaDropMercadoFiltroBase()
        {
            try
            {
                using (NewTierraEntities n = new NewTierraEntities())
                {
                    ddlMercadoFiltro_Base.DataSource = n.Mercadoes.ToList();
                    ddlMercadoFiltro_Base.DataValueField = "Mercado_id";
                    ddlMercadoFiltro_Base.DataTextField = "Mercado_nome";
                    ddlMercadoFiltro_Base.DataBind();
                }
            }
            catch (Exception ex)
            {
                System.Diagnostics.StackTrace trace = new System.Diagnostics.StackTrace(ex, true);
                Log.Save((trace.GetFrame(0).GetMethod().ReflectedType.FullName), ("Linha: " + trace.GetFrame(0).GetFileLineNumber()), ("Column: " + trace.GetFrame(0).GetFileColumnNumber()), ex.Message);

                lblMsgCadMServicos.Text = ex.Message;
            }
        }

        protected void PopulaDropBaseTarifariaFiltroBase()
        {
            try
            {
                using (NewTierraEntities n = new NewTierraEntities())
                {
                    ddlBaseTarifariaFiltro_Base.DataSource = n.BaseTarifarias.ToList();
                    ddlBaseTarifariaFiltro_Base.DataValueField = "BaseTarifaria_id";
                    ddlBaseTarifariaFiltro_Base.DataTextField = "BaseTarifaria_nome";
                    ddlBaseTarifariaFiltro_Base.DataBind();
                }
            }
            catch (Exception ex)
            {
                System.Diagnostics.StackTrace trace = new System.Diagnostics.StackTrace(ex, true);
                Log.Save((trace.GetFrame(0).GetMethod().ReflectedType.FullName), ("Linha: " + trace.GetFrame(0).GetFileLineNumber()), ("Column: " + trace.GetFrame(0).GetFileColumnNumber()), ex.Message);

                lblMsgCadMServicos.Text = ex.Message;
            }
        }

        protected void PopulaDropMoedaFiltroBase()
        {
            try
            {
                using (NewTierraEntities Con = new NewTierraEntities())
                {
                    ddlMoedaFiltro_Base.DataSource = Con.Moeda.ToList();
                    ddlMoedaFiltro_Base.DataTextField = "Moeda_sigla";
                    ddlMoedaFiltro_Base.DataValueField = "Moeda_id";
                    ddlMoedaFiltro_Base.DataBind();
                }

            }
            catch (Exception ex)
            {
                System.Diagnostics.StackTrace trace = new System.Diagnostics.StackTrace(ex, true);
                Log.Save((trace.GetFrame(0).GetMethod().ReflectedType.FullName), ("Linha: " + trace.GetFrame(0).GetFileLineNumber()), ("Column: " + trace.GetFrame(0).GetFileColumnNumber()), ex.Message);

                lblMsgCadMServicos.Text = ex.Message;
            }
        }

        protected void popularDropTipoBaseFiltroBase()
        {
            try
            {
                using (NewTierraEntities Con = new NewTierraEntities())
                {
                    ddlTipoBase_Base.DataSource = Con.Tipo_Base.OrderBy(t => t.TipoBase_nome).ToList();
                    ddlTipoBase_Base.DataTextField = "TipoBase_nome";
                    ddlTipoBase_Base.DataValueField = "TipoBase_id";
                    ddlTipoBase_Base.DataBind();

                    ddlTipoBase_Base.SelectedValue = "2";

                    //ddlTipoTransporte.Items.Insert(0, new ListItem("Selecione...", "0"));
                }
            }
            catch (Exception ex)
            {
                System.Diagnostics.StackTrace trace = new System.Diagnostics.StackTrace(ex, true);
                Log.Save((trace.GetFrame(0).GetMethod().ReflectedType.FullName), ("Linha: " + trace.GetFrame(0).GetFileLineNumber()), ("Column: " + trace.GetFrame(0).GetFileColumnNumber()), ex.Message);

                lblMsgCadMServicos.Text = ex.Message;
            }
        }

        //protected void popularDropTipoServico3()
        //{
        //    try
        //    {
        //        using (NewTierraEntities Con = new NewTierraEntities())
        //        {
        //            ddlTipoServico3.DataSource = Con.S_Servicos_Tipo.ToList();
        //            ddlTipoServico3.DataTextField = "Tipo_Nome";
        //            ddlTipoServico3.DataValueField = "Tipo_Id";
        //            ddlTipoServico3.DataBind();

        //            ddlTipoServico3.Items.Insert(0, new ListItem("Selecione...", "0"));
        //        }
        //    }
        //    catch (Exception ex)
        //    {
        //        System.Diagnostics.StackTrace trace = new System.Diagnostics.StackTrace(ex, true);
        //        Log.Save((trace.GetFrame(0).GetMethod().ReflectedType.FullName), ("Linha: " + trace.GetFrame(0).GetFileLineNumber()), ("Column: " + trace.GetFrame(0).GetFileColumnNumber()), ex.Message);

        //        lblMsgCadMServicos.Text = ex.Message;
        //    }
        //}

        //protected void popularDropItemSubServico()
        //{
        //    try
        //    {
        //        ItemSubServicoDAL isd = new ItemSubServicoDAL();

        //        ddlItemSubServico.DataSource = isd.ListarTodos();
        //        ddlItemSubServico.DataTextField = "ItemSubServico_nome";
        //        ddlItemSubServico.DataValueField = "ItemSubServico_id";
        //        ddlItemSubServico.DataBind();

        //        ddlItemSubServico.Items.Insert(0, new ListItem("Selecione...", "0"));

        //    }
        //    catch (Exception ex)
        //    {
        //        System.Diagnostics.StackTrace trace = new System.Diagnostics.StackTrace(ex, true);
        //        Log.Save((trace.GetFrame(0).GetMethod().ReflectedType.FullName), ("Linha: " + trace.GetFrame(0).GetFileLineNumber()), ("Column: " + trace.GetFrame(0).GetFileColumnNumber()), ex.Message);

        //        lblMsgCadMServicos.Text = ex.Message;
        //    }
        //}

        protected void popularDropPeriodosCopiarMServicoSozinho()
        {
            try
            {

                MontaServicoDAL ms = new MontaServicoDAL();

                ddlPeriodosMServicoSozinho.DataSource = ms.ListarTodosCondicaoMServico(Convert.ToInt32(ViewState["IdSupplier"]), Convert.ToInt32(Session["IdServico"]));
                ddlPeriodosMServicoSozinho.DataTextField = "MServico_DataFrom";
                ddlPeriodosMServicoSozinho.DataValueField = "IdMServico";
                ddlPeriodosMServicoSozinho.DataBind();

            }
            catch (Exception ex)
            {
                System.Diagnostics.StackTrace trace = new System.Diagnostics.StackTrace(ex, true);
                Log.Save((trace.GetFrame(0).GetMethod().ReflectedType.FullName), ("Linha: " + trace.GetFrame(0).GetFileLineNumber()), ("Column: " + trace.GetFrame(0).GetFileColumnNumber()), ex.Message);

                lblMsgCadMServicos.Text = ex.Message;
            }
        }

        protected void popularDropTemporadasCadastradasSubServ(int IdSupplier, int IdServico)
        {
            try
            {

                MontaServicoDAL ms = new MontaServicoDAL();

                ddlTemporadasCadastradasSubServ.DataSource = ms.ListarTodosSubServicoSub(IdSupplier, IdServico);
                ddlTemporadasCadastradasSubServ.DataTextField = "MServico_DataFrom";
                ddlTemporadasCadastradasSubServ.DataValueField = "IdMServico";
                ddlTemporadasCadastradasSubServ.DataBind();

            }
            catch (Exception ex)
            {
                System.Diagnostics.StackTrace trace = new System.Diagnostics.StackTrace(ex, true);
                Log.Save((trace.GetFrame(0).GetMethod().ReflectedType.FullName), ("Linha: " + trace.GetFrame(0).GetFileLineNumber()), ("Column: " + trace.GetFrame(0).GetFileColumnNumber()), ex.Message);

                MostrarMsg(ex.Message);
            }
        }

        protected void PopulaGridBase(int IdMServico)
        {
            try
            {
                SupplierDAL sp = new SupplierDAL();
                SBasesDAL bd = new SBasesDAL();
                CambioDAL camd = new CambioDAL();
                SBaseValorDAL sbval = new SBaseValorDAL();

                //IdMServico = 221;

                if (!txtSupplier.Text.Equals(""))
                {
                    if (IdMServico == 0)
                    {
                        Supplier s = sp.FindAllNome(txtSupplier.Text);

                        ViewState["IdSupplierSubServicoPrincipal"] = s.S_id;

                        GridBases.DataSource = bd.ObterPorIdSupplierBaseIndex(s.S_id, Convert.ToInt32(rdoBasesIndexSubServico.SelectedValue));
                        GridBases.DataBind();


                        lblMoedaBaseSubServ.Text = "Moeda: " + bd.ObterUmPorIdSupplierIndex(s.S_id, Convert.ToInt32(rdoBasesIndexSubServico.SelectedValue)).Moeda.Moeda_sigla;
                        ViewState["IdMoedaBaseSubServico"] = bd.ObterUmPorIdSupplierIndex(s.S_id, Convert.ToInt32(rdoBasesIndexSubServico.SelectedValue)).Moeda.Moeda_id;

                        PopulaGridTemporadasSubServicos(s.S_id, Convert.ToInt32(Session["IdServico"]));
                        popularDropTemporadasCadastradasSubServ(s.S_id, Convert.ToInt32(Session["IdServico"]));
                        PopulaGridSubServAdicionados(IdMServico);
                    }
                    else
                    {
                        Supplier s = sp.FindAllNome(txtSupplier.Text);

                        rdoBasesIndexSubServico.SelectedValue = sbval.ObterPorIdMServ(IdMServico).S_Bases.Base_index.ToString();

                        ViewState["IdSupplierSubServicoPrincipal"] = s.S_id;
                        popularDropTemporadasCadastradasSubServ(s.S_id, Convert.ToInt32(Session["IdServico"]));

                        GridBases.DataSource = bd.ObterPorIdSupplierBase(s.S_id, IdMServico, Convert.ToInt32(rdoBasesIndexSubServico.SelectedValue));
                        GridBases.DataBind();

                        lblMoedaBaseSubServ.Text = "Moeda: " + bd.ObterUmPorIdSupplierIndex(s.S_id, Convert.ToInt32(rdoBasesIndexSubServico.SelectedValue)).Moeda.Moeda_sigla;
                        ViewState["IdMoedaBaseSubServico"] = bd.ObterUmPorIdSupplierIndex(s.S_id, Convert.ToInt32(rdoBasesIndexSubServico.SelectedValue)).Moeda.Moeda_id;

                        DataBoundGridBase(IdMServico);
                        PopulaGridSubServAdicionados(IdMServico);
                        PopulaGridTemporadasSubServicos(s.S_id, Convert.ToInt32(Session["IdServico"]));
                    }
                }
                else
                {
                    GridBases.DataSource = bd.ObterPorIdSupplierBaseIndex(0, Convert.ToInt32(rdoBasesIndexSubServico.SelectedValue));
                    GridBases.DataBind();
                }

            }
            catch (Exception ex)
            {
                System.Diagnostics.StackTrace trace = new System.Diagnostics.StackTrace(ex, true);
                Log.Save((trace.GetFrame(0).GetMethod().ReflectedType.FullName), ("Linha: " + trace.GetFrame(0).GetFileLineNumber()), ("Column: " + trace.GetFrame(0).GetFileColumnNumber()), ex.Message);

                lblMsgCadServicos.Text = ex.Message;
            }
        }

        protected void DataBoundGridBase(int IdMServico)
        {
            try
            {
                SBasesDAL bd = new SBasesDAL();
                SBaseValorDAL sbvd = new SBaseValorDAL();

                foreach (GridViewRow item in GridBases.Rows)
                {
                    int IdBase = Convert.ToInt32(item.Cells[3].Text);

                    S_Bases_Valor sbv = sbvd.ObterPorIds(IdMServico, IdBase);

                    Label lblValorBase = (Label)item.FindControl("lblValorBase");

                    lblValorBase.Text = Convert.ToString(sbv.S_Bases_Valor_valor);
                }

            }
            catch (Exception ex)
            {
                System.Diagnostics.StackTrace trace = new System.Diagnostics.StackTrace(ex, true);
                Log.Save((trace.GetFrame(0).GetMethod().ReflectedType.FullName), ("Linha: " + trace.GetFrame(0).GetFileLineNumber()), ("Column: " + trace.GetFrame(0).GetFileColumnNumber()), ex.Message);

                lblMsgCadSubServico.Text = ex.Message;
            }
        }

        protected void PopulaGridTemporadasSubServicos(int IdSupplier, int IdServico)
        {
            try
            {
                MontaServicoDAL ms = new MontaServicoDAL();

                GridTemporadasSubServicos.DataSource = ms.ListarTodosSubServicoSub(IdSupplier, IdServico);
                GridTemporadasSubServicos.DataBind();

                if (GridTemporadasSubServicos.Rows.Count > 0)
                {
                    btnCopiarTemporadaSubServ.Visible = true;
                }
                else
                {
                    btnCopiarTemporadaSubServ.Visible = false;
                }

            }
            catch (Exception ex)
            {
                System.Diagnostics.StackTrace trace = new System.Diagnostics.StackTrace(ex, true);
                Log.Save((trace.GetFrame(0).GetMethod().ReflectedType.FullName), ("Linha: " + trace.GetFrame(0).GetFileLineNumber()), ("Column: " + trace.GetFrame(0).GetFileColumnNumber()), ex.Message);

                lblMsgCadSubServico.Text = ex.Message;
            }
        }

        protected void PopulaGridServicoSozinho(int index)
        {
            try
            {
                SBasesDAL b = new SBasesDAL();
                SupplierDAL s = new SupplierDAL();
                MontaServicoDAL ms = new MontaServicoDAL();

                Supplier sp = s.ObterSupplierPorNome(txtSupplierMontaServico.Text);
                ViewState["IdSupplier"] = sp.S_id;

                if (b.ListarTodosPorSupplier(sp.S_id, index, Convert.ToInt32(ddlMercadoFiltro_Base.SelectedValue), Convert.ToInt32(ddlBaseTarifariaFiltro_Base.SelectedValue), Convert.ToInt32(ddlMoedaFiltro_Base.SelectedValue), Convert.ToInt32(ddlTipoBase_Base.SelectedValue)).Count() == 0)
                {
                    MostrarMsg("Não existe bases cadastradas para este supplier.");
                    btnSalvarTarifas.Visible = false;
                }
                else
                {
                    btnSalvarTarifas.Visible = true;
                    rdoBasesIndex.SelectedValue = index.ToString();
                    lblMsgCadMServicos.Text = "";
                }


                GridBaseSupplierServicoSozinho.DataSource = b.ListarTodosPorSupplier(sp.S_id, index, Convert.ToInt32(ddlMercadoFiltro_Base.SelectedValue), Convert.ToInt32(ddlBaseTarifariaFiltro_Base.SelectedValue), Convert.ToInt32(ddlMoedaFiltro_Base.SelectedValue), Convert.ToInt32(ddlTipoBase_Base.SelectedValue));
                GridBaseSupplierServicoSozinho.DataBind();

                if (!txtCodMServicoSozinho.Text.Equals(""))
                {
                    PopulaIntoGridBaseSupplierServicoSozinho(GridBaseSupplierServicoSozinho);
                }
            }
            catch (Exception ex)
            {
                System.Diagnostics.StackTrace trace = new System.Diagnostics.StackTrace(ex, true);
                Log.Save((trace.GetFrame(0).GetMethod().ReflectedType.FullName), ("Linha: " + trace.GetFrame(0).GetFileLineNumber()), ("Column: " + trace.GetFrame(0).GetFileColumnNumber()), ex.Message);

                lblMsgCadMServicos.Text = ex.Message;
            }
        }

        protected void PopulaIntoGridBaseSupplierServicoSozinho(GridView nome)
        {
            try
            {
                MontaServicoValoresDAL msv = new MontaServicoValoresDAL();

                List<Monta_Servico_Valores> listaValores = msv.ListaTodos(Convert.ToInt32(txtCodMServicoSozinho.Text));


                foreach (GridViewRow item in nome.Rows)
                {

                    DropDownList ddlStatusTarifa = (DropDownList)item.FindControl("ddlStatusTarifa");
                    DropDownList ddlTipoCadastro = (DropDownList)item.FindControl("ddlTipoCadastro");

                    TextBox txtValorServicoSozinhoVenda = (TextBox)item.FindControl("txtValorServicoSozinhoVenda");
                    TextBox txtValorServicoSozinho = (TextBox)item.FindControl("txtValorServicoSozinho");
                    string baseID = item.Cells[5].Text;
                    Label lblValorServicoSozinhoTotal = (Label)item.FindControl("lblValorServicoSozinhoTotal");
                    Label lblIDValores = (Label)item.FindControl("lblIDValores");

                    foreach (Monta_Servico_Valores lista in listaValores)
                    {
                        if (lista.Base_id == Convert.ToInt32(baseID))
                        {
                            if (lista.MServico_Valores_Bulk == null)
                            {
                                ddlTipoCadastro.SelectedValue = "1";

                                PopulaDropStatusTarifa(ddlStatusTarifa);

                                ddlStatusTarifa.SelectedValue = lista.S_mercado_tarifa_status_id.ToString();

                                ddlStatusTarifa.Visible = true;
                                txtValorServicoSozinho.Visible = false;
                                txtValorServicoSozinhoVenda.Visible = false;

                                lblIDValores.Text = Convert.ToString(lista.IdMServicoValores);
                            }
                            else
                            {
                                txtValorServicoSozinhoVenda.Text = Convert.ToString(lista.MServico_Valores_Bulk_Venda);
                                txtValorServicoSozinho.Text = Convert.ToString(lista.MServico_Valores_Bulk);
                                lblValorServicoSozinhoTotal.Text = Convert.ToString(lista.MServico_Valores_Bulk_Total);
                                lblIDValores.Text = Convert.ToString(lista.IdMServicoValores);

                                ddlStatusTarifa.Visible = false;
                                txtValorServicoSozinho.Visible = true;
                            }

                        }
                    }
                }

            }
            catch (Exception ex)
            {
                System.Diagnostics.StackTrace trace = new System.Diagnostics.StackTrace(ex, true);
                Log.Save((trace.GetFrame(0).GetMethod().ReflectedType.FullName), ("Linha: " + trace.GetFrame(0).GetFileLineNumber()), ("Column: " + trace.GetFrame(0).GetFileColumnNumber()), ex.Message);

                lblMsgCadMServicos.Text = ex.Message;
            }
        }

        protected void PopulaGridSubServAdicionados(int IdMServico)
        {
            try
            {

                ServicoCompletoDAL scd = new ServicoCompletoDAL();

                GridSubServAdicionados.DataSource = scd.ListarTodosSubServico(Convert.ToInt32(Session["IdServico"]), IdMServico);
                GridSubServAdicionados.DataBind();

                if (scd.ListarTodosSubServico(Convert.ToInt32(Session["IdServico"]), IdMServico) != null)
                {
                    btnCalculaServico.Visible = true;
                }

                //Servico_Completo sc = scd.ObterPorId(1);
                //string teste = sc.Monta_Servico..Tipo_categ_nome;
            }
            catch (Exception ex)
            {
                lblMsgCadServicos.Text = ex.Message;
            }
        }

        protected void PopulaGridMServicosSozinhoCadastrados()
        {
            try
            {
                MontaServicoDAL ms = new MontaServicoDAL();

                GridMServicosSozinhoCadastrados.DataSource = ms.ListarTodosCondicaoMServico(Convert.ToInt32(ViewState["IdSupplier"]), Convert.ToInt32(Session["IdServico"]));
                GridMServicosSozinhoCadastrados.DataBind();

            }
            catch (Exception ex)
            {
                System.Diagnostics.StackTrace trace = new System.Diagnostics.StackTrace(ex, true);
                Log.Save((trace.GetFrame(0).GetMethod().ReflectedType.FullName), ("Linha: " + trace.GetFrame(0).GetFileLineNumber()), ("Column: " + trace.GetFrame(0).GetFileColumnNumber()), ex.Message);

                lblMsgCadMServicos.Text = ex.Message;
            }
        }

        protected void PopulaGridServPorSupp(int IdSupplier)
        {
            try
            {
                ServicoCompletoDAL scd = new ServicoCompletoDAL();

                GridServPorSupp.DataSource = scd.ListarTodosServPorSupplier(IdSupplier);
                GridServPorSupp.DataBind();

                MergeCellsServPorSupp();
            }
            catch (Exception ex)
            {
                System.Diagnostics.StackTrace trace = new System.Diagnostics.StackTrace(ex, true);
                Log.Save((trace.GetFrame(0).GetMethod().ReflectedType.FullName), ("Linha: " + trace.GetFrame(0).GetFileLineNumber()), ("Column: " + trace.GetFrame(0).GetFileColumnNumber()), ex.Message);

                lblMsgCadServPorSupp.Text = ex.Message;
            }
        }

        private void MergeCellsServPorSupp()
        {
            int i = GridServPorSupp.Rows.Count - 2;
            while (i >= 0)
            {
                GridViewRow curRow = GridServPorSupp.Rows[i];
                GridViewRow preRow = GridServPorSupp.Rows[i + 1];

                int j = 0;
                while (j < curRow.Cells.Count)
                {
                    if (curRow.Cells[j].Text == preRow.Cells[j].Text)
                    {
                        if (preRow.Cells[j].RowSpan < 2)
                        {
                            curRow.Cells[j].RowSpan = 2;
                            preRow.Cells[j].Visible = false;
                        }
                        else
                        {
                            curRow.Cells[j].RowSpan = preRow.Cells[j].RowSpan + 1;
                            preRow.Cells[j].Visible = false;
                        }
                    }
                    j++;
                }
                i--;
            }
        }







        protected void PopulaDropPaisReport()
        {
            try
            {
                PaisDAL pd = new PaisDAL();

                ddlPaisReport.DataSource = pd.ListarTodos().ToList().OrderBy(p => p.PAIS_nome);
                ddlPaisReport.DataValueField = "PAIS_id";
                ddlPaisReport.DataTextField = "PAIS_nome";
                ddlPaisReport.DataBind();
            }
            catch (Exception ex)
            {
                MostrarMsg(ex.Message);
            }
        }


        protected void PopulaDropPaisReportTarifario()
        {
            try
            {
                PaisDAL pd = new PaisDAL();

                ddlPaisReportTarifario.DataSource = pd.ListarTodos().ToList().OrderBy(p => p.PAIS_nome);
                ddlPaisReportTarifario.DataValueField = "PAIS_id";
                ddlPaisReportTarifario.DataTextField = "PAIS_nome";
                ddlPaisReportTarifario.DataBind();
            }
            catch (Exception ex)
            {
                MostrarMsg(ex.Message);
            }
        }


        protected void ddlPaisReport_SelectedIndexChanged(object sender, EventArgs e)
        {
            PopulaDropCidadeReport();
            //ModalPopupExtenderReport.Show();
        }

        protected void PopulaDropCidadeReport()
        {
            try
            {
                CidadeDAL cd = new CidadeDAL();

                int idPais = Convert.ToInt32(ddlPaisReport.SelectedValue);
                ddlCidadeReport.DataSource = cd.ListarTodos().OrderBy(c => c.CID_nome).ToList();
                ddlCidadeReport.DataValueField = "CID_id";
                ddlCidadeReport.DataTextField = "CID_nome";
                ddlCidadeReport.DataBind();

                ddlCidadeReport.Items.Insert(0, new ListItem("Selecione...", "0"));

            }
            catch (Exception ex)
            {
                MostrarMsg(ex.Message);
            }
        }



        protected void PopulaDropCidadeReportTarifario()
        {
            try
            {
                CidadeDAL cd = new CidadeDAL();

                int idPais = Convert.ToInt32(ddlPaisReportTarifario.SelectedValue);
                ddlCidadeRerpotTarifario.DataSource = cd.ListarTodos().OrderBy(c => c.CID_nome).ToList();
                ddlCidadeRerpotTarifario.DataValueField = "CID_id";
                ddlCidadeRerpotTarifario.DataTextField = "CID_nome";
                ddlCidadeRerpotTarifario.DataBind();

                ddlCidadeRerpotTarifario.Items.Insert(0, new ListItem("Selecione...", "0"));

            }
            catch (Exception ex)
            {
                MostrarMsg(ex.Message);
            }
        }


        protected void PopulaDropCambioReport()
        {
            try
            {
                MoedaDAL cd = new MoedaDAL();

                ddlCambioReport.DataSource = cd.ListarTodos().ToList();
                ddlCambioReport.DataValueField = "Moeda_id";
                ddlCambioReport.DataTextField = "Moeda_sigla";
                ddlCambioReport.DataBind();

                ddlCambioReport.Items.Insert(0, new ListItem("Selecione...", "0"));

            }
            catch (Exception ex)
            {
                MostrarMsg(ex.Message);
            }
        }


        protected void PopulaDropCambioReportTarifario()
        {
            try
            {
                MoedaDAL cd = new MoedaDAL();

                ddlCambioReportTarifario.DataSource = cd.ListarTodos().ToList();
                ddlCambioReportTarifario.DataValueField = "Moeda_id";
                ddlCambioReportTarifario.DataTextField = "Moeda_sigla";
                ddlCambioReportTarifario.DataBind();

                ddlCambioReportTarifario.Items.Insert(0, new ListItem("Selecione...", "0"));

            }
            catch (Exception ex)
            {
                MostrarMsg(ex.Message);
            }
        }

        protected void PopulaDropMercadoReport()
        {
            try
            {
                using (NewTierraEntities n = new NewTierraEntities())
                {
                    ddlMercadoReport.DataSource = n.Mercadoes.ToList();
                    ddlMercadoReport.DataValueField = "Mercado_id";
                    ddlMercadoReport.DataTextField = "Mercado_nome";
                    ddlMercadoReport.DataBind();

                    ddlMercadoReport.Items.Insert(0, new ListItem("Selecione...", "0"));
                }
            }
            catch (Exception ex)
            {
                MostrarMsg(ex.Message);
            }
        }


        protected void PopulaDropMercadoReportTarifario()
        {
            try
            {
                using (NewTierraEntities n = new NewTierraEntities())
                {
                    ddlMercadoReportTarifario.DataSource = n.Mercadoes.ToList();
                    ddlMercadoReportTarifario.DataValueField = "Mercado_id";
                    ddlMercadoReportTarifario.DataTextField = "Mercado_nome";
                    ddlMercadoReportTarifario.DataBind();

                    ddlMercadoReportTarifario.Items.Insert(0, new ListItem("Selecione...", "0"));
                }
            }
            catch (Exception ex)
            {
                MostrarMsg(ex.Message);
            }
        }


        protected void popularDropBaseTarifariaReport()
        {
            try
            {
                using (NewTierraEntities n = new NewTierraEntities())
                {
                    ddlBaseTarifariaReport.DataSource = n.BaseTarifarias.ToList();
                    ddlBaseTarifariaReport.DataValueField = "BaseTarifaria_id";
                    ddlBaseTarifariaReport.DataTextField = "BaseTarifaria_nome";
                    ddlBaseTarifariaReport.DataBind();

                    ddlBaseTarifariaReport.Items.Insert(0, new ListItem("Selecione...", "0"));
                }

            }
            catch (Exception ex)
            {
                MostrarMsg(ex.Message);
            }
        }

        protected void popularDropBaseTarifariaReportTarifario()
        {
            try
            {
                using (NewTierraEntities n = new NewTierraEntities())
                {
                    ddlBaseTarifariaReportTarifario.DataSource = n.BaseTarifarias.ToList();
                    ddlBaseTarifariaReportTarifario.DataValueField = "BaseTarifaria_id";
                    ddlBaseTarifariaReportTarifario.DataTextField = "BaseTarifaria_nome";
                    ddlBaseTarifariaReportTarifario.DataBind();

                    ddlBaseTarifariaReportTarifario.Items.Insert(0, new ListItem("Selecione...", "0"));
                }

            }
            catch (Exception ex)
            {
                MostrarMsg(ex.Message);
            }
        }


        #endregion

        #region CRUD Servicos

        protected void CadastrarServico(object sender, EventArgs e)
        {
            ServicoDAL d = new ServicoDAL();

            if (txtCodServico.Text != "")
            {
                LimpaCampos(this.Controls);
                lblMsgCadServicos.Text = "";
                btnNovoServico.Text = "Salvar";
                PanelbtnsServico.Visible = false;
                EditorInfoLongServicos.Content = "";
                EditorInfoShortServicos.Content = "";
                //Session.Abandon();
                btnAtualizarServico.Visible = false;
                txtNomeServico.Focus();
                lblServicoNomeTituloTXT.Text = "";
                PopularDrops();
                return;
            }

            if (d.VerificaExiste(txtNomeServico.Text, Convert.ToInt32(ddlCidadeServicos.SelectedValue), 0))
            {
                MostrarMsg("Já existe serviço cadastrado com esse nome nessa cidade, tente outro.");
                return;
            }

            if (ddlCidadeServicos.SelectedValue.Equals("0"))
            {
                MostrarMsg("Favor selecione uma cidade.");
                return;
            }

            if (ddlTipoServico.SelectedValue.Equals("0"))
            {
                MostrarMsg("Favor selecione um tipo de serviço.");
                return;
            }

            try
            {
                S_Servicos s = new S_Servicos();

                s.Servicos_Nome = txtNomeServico.Text;
                s.Servicos_descr = EditorInfoLongServicos.Content;
                s.Servicos_descrCurt = EditorInfoShortServicos.Content;
                s.Servicos_descrRemarks = txtremarks.Text;
                s.Servicos_descrVoucher = txtInfoVoucher.Text;
                s.Servicos_descrCliente = txtInfoCliente.Text;
                s.STATUS_id = Convert.ToInt32(ddlStatusServicos.SelectedValue);
                s.Tipo_Id = Convert.ToInt32(ddlTipoServico.SelectedValue);
                s.Cid_Id = Convert.ToInt32(ddlCidadeServicos.SelectedValue);
                s.Pais_Id = Convert.ToInt32(ddlPaisServicos.SelectedValue);

                s.Recommended = chkRecommended.Checked;

                if (chkSIB.Checked) s.SIB = true; else s.SIB = false;

                if (ddlTipoServico.SelectedItem.ToString().Equals("Transfer"))
                {
                    s.Servicos_transfer = "S";
                }
                else
                {
                    s.Servicos_transfer = null;
                }

                if (ddlTipoServicoCateg.SelectedValue.Equals("0"))
                { s.Tipo_categ_id = null; }
                else
                { s.Tipo_categ_id = Convert.ToInt32(ddlTipoServicoCateg.SelectedValue); }

                d.Salvar(s);
                //LimpaCampos(this.Controls);
                CarregarServicoNome(sender, e, s);
                MostrarMsg("Serviço cadastrado com sucesso.");

            }
            catch (Exception ex)
            {
                System.Diagnostics.StackTrace trace = new System.Diagnostics.StackTrace(ex, true);
                Log.Save((trace.GetFrame(0).GetMethod().ReflectedType.FullName), ("Linha: " + trace.GetFrame(0).GetFileLineNumber()), ("Column: " + trace.GetFrame(0).GetFileColumnNumber()), ex.Message);

                lblMsgCadServicos.Text = ex.Message;
            }
        }

        protected void AtualizarServico(object sender, EventArgs e)
        {
            if (txtCodServico.Text == "")
            {
                MostrarMsg("Selecione um serviço para ser atualizado.");
                return;
            }

            if (ddlCidadeServicos.SelectedValue.Equals("0"))
            {
                MostrarMsg("Favor selecione uma cidade.");
                return;
            }

            if (ddlTipoServico.SelectedValue.Equals("0"))
            {
                MostrarMsg("Favor selecione um tipo de serviço.");
                return;
            }

            try
            {
                ServicoDAL d = new ServicoDAL();

                if (d.VerificaExiste(txtNomeServico.Text, Convert.ToInt32(ddlCidadeServicos.SelectedValue), Convert.ToInt32(txtCodServico.Text)))
                {
                    MostrarMsg("Já existe serviço cadastrado com esse nome nessa cidade, tente outro.");
                    return;
                }

                S_Servicos s = new S_Servicos();

                s.Servicos_Id = Convert.ToInt32(txtCodServico.Text);
                s.Servicos_Nome = txtNomeServico.Text;
                s.Servicos_descr = EditorInfoLongServicos.Content;
                s.Servicos_descrCurt = EditorInfoShortServicos.Content;
                s.Servicos_descrRemarks = txtremarks.Text;
                s.Servicos_descrVoucher = txtInfoVoucher.Text;
                s.Servicos_descrCliente = txtInfoCliente.Text;
                s.STATUS_id = Convert.ToInt32(ddlStatusServicos.SelectedValue);
                s.Tipo_Id = Convert.ToInt32(ddlTipoServico.SelectedValue);
                s.Cid_Id = Convert.ToInt32(ddlCidadeServicos.SelectedValue);
                s.Pais_Id = Convert.ToInt32(ddlPaisServicos.SelectedValue);
                s.Recommended = chkRecommended.Checked;

                if (chkSIB.Checked) s.SIB = true; else s.SIB = false;

                if (ddlTipoServico.SelectedItem.ToString().Equals("Transfer"))
                {
                    s.Servicos_transfer = "S";
                }
                else
                {
                    s.Servicos_transfer = null;
                }

                if (ddlTipoServicoCateg.SelectedValue.Equals("0"))
                { s.Tipo_categ_id = null; }
                else
                { s.Tipo_categ_id = Convert.ToInt32(ddlTipoServicoCateg.SelectedValue); }

                d.Atualizar(s);

                FileTransfersDAL ftd = new FileTransfersDAL();

                List<File_Transfers> filesTrf = ftd.ListarTodos(lblServicoNomeTituloTXT.Text);

                foreach (File_Transfers item in filesTrf)
                {
                    File_Transfers ft = new File_Transfers();
                    ft.Transf_nome = txtNomeServico.Text;
                    ft.File_Transf_id = item.File_Transf_id;

                    ftd.AtualizarNome(ft);
                }


                CarregarServicoNome(sender, e, s);
                //LimpaCampos(this.Controls);
                MostrarMsg("Serviço atualizado com sucesso.");

            }
            catch (Exception ex)
            {
                System.Diagnostics.StackTrace trace = new System.Diagnostics.StackTrace(ex, true);
                Log.Save((trace.GetFrame(0).GetMethod().ReflectedType.FullName), ("Linha: " + trace.GetFrame(0).GetFileLineNumber()), ("Column: " + trace.GetFrame(0).GetFileColumnNumber()), ex.Message);

                lblMsgCadServicos.Text = ex.Message;
            }
        }

        protected void ExcluirServico(object sender, EventArgs e)
        {
            if (txtCodServico.Text == "")
            {
                MostrarMsg("Selecione um serviço para ser excluído.");
                return;
            }

            if (!ExcluiFotoPasta())
            {
                MostrarMsg("Não foi possível deletar as fotos na pasta 'Galeria/Servicos' por favor tente novamente.");
                return;
            }

            try
            {
                ServicoDAL s = new ServicoDAL();

                S_Servicos si = s.ObterPorId(Convert.ToInt32(txtCodServico.Text));
                s.Excluir(si);
                Session.Remove("IdServico");
                //Session.Abandon();
                LimpaCampos(this.Controls);
                PanelbtnsServico.Visible = false;
                MostrarMsg("Serviço excluído com sucesso.");

            }
            catch (Exception ex)
            {
                System.Diagnostics.StackTrace trace = new System.Diagnostics.StackTrace(ex, true);
                Log.Save((trace.GetFrame(0).GetMethod().ReflectedType.FullName), ("Linha: " + trace.GetFrame(0).GetFileLineNumber()), ("Column: " + trace.GetFrame(0).GetFileColumnNumber()), ex.Message);

                lblMsgCadServicos.Text = ex.Message;
            }
        }

        public bool ExcluiFotoPasta()
        {
            try
            {
                FotoServicoDAL f = new FotoServicoDAL();

                foreach (Servicos_Imagem p in f.ListarTodosLista(Convert.ToInt32(txtCodServico.Text)))
                {
                    string path = "~/Galeria/Servicos/" + Session["IdServico"] + "/" + p.Serv_img_nome;
                    System.IO.File.Delete(Server.MapPath(path));
                }
                return true;
            }
            catch (Exception ex)
            {
                System.Diagnostics.StackTrace trace = new System.Diagnostics.StackTrace(ex, true);
                Log.Save((trace.GetFrame(0).GetMethod().ReflectedType.FullName), ("Linha: " + trace.GetFrame(0).GetFileLineNumber()), ("Column: " + trace.GetFrame(0).GetFileColumnNumber()), ex.Message);

                lblMsgCadServicos.Text = ex.Message;
                return false;
            }
        }

        #endregion

        #region Regras SubServiços

        protected void rdoBasesSubServicoIndex_SelectedIndexChanged(object sender, EventArgs e)
        {
            PopulaGridBase(0);
        }

        protected void btnTemporadasCadastradas_Click(object sender, EventArgs e)
        {
            btnCalculaServico.Visible = true;
            btnOpenAddSubServicos.Visible = true;
            imgRefresh.Visible = true;
        }

        protected void btnOpenAddSubServicos_Click(object sender, EventArgs e)
        {

            string script = "";
            script = script + "window.open('AddSupplierTarifas.aspx?from=" + txtDataFromSubServico.Text + "&to=" + txtDataToSubServico.Text + "&idMS=" + ViewState["IdMontaSubServico"].ToString() + "&Index=" + rdoBasesIndexSubServico.SelectedValue + "','', " + "'status=1, scrollbars=yes, width=820, height=620, top=0, left=0');";
            ScriptManager.RegisterStartupScript(this, this.GetType(), "Descritivo", script, true);

            PopulaGridSubServAdicionados(Convert.ToInt32(ViewState["IdMontaSubServico"]));
        }

        protected void ExluirServCompleto(object sender, CommandEventArgs e)
        {
            try
            {
                string[] pars = e.CommandArgument.ToString().Split(',');

                int myid = Convert.ToInt32(pars[0]);

                ServicoCompletoDAL scd = new ServicoCompletoDAL();

                Servico_Completo sc = scd.ObterPorIdMServicoTemp(myid, Convert.ToInt32(ViewState["IdMontaSubServico"]), Convert.ToInt32(pars[1]));

                scd.Excluir(sc);

                PopulaGridSubServAdicionados(Convert.ToInt32(ViewState["IdMontaSubServico"]));
                CalculaServico();

                MostrarMsg("Registro excluído com sucesso.");
            }
            catch (Exception ex)
            {
                System.Diagnostics.StackTrace trace = new System.Diagnostics.StackTrace(ex, true);
                Log.Save((trace.GetFrame(0).GetMethod().ReflectedType.FullName), ("Linha: " + trace.GetFrame(0).GetFileLineNumber()), ("Column: " + trace.GetFrame(0).GetFileColumnNumber()), ex.Message);

                lblMsgCadSubServico.Text = ex.Message;
            }
        }

        protected void btnNovaTemporadaSubServico_Click(object sender, EventArgs e)
        {
            try
            {
                if (Convert.ToInt32(ViewState["NovaTemporadaSubServico"]) == 0)
                {
                    Monta_Servico ms = new Monta_Servico();
                    MontaServicoDAL msd = new MontaServicoDAL();

                    ms.MServico_DataFrom = Convert.ToDateTime(txtDataFromSubServico.Text);
                    ms.MServico_DataTo = Convert.ToDateTime(txtDataToSubServico.Text);
                    ms.S_id = Convert.ToInt32(ViewState["IdSupplierSubServicoPrincipal"]);
                    //ms.Tipo_Id = Convert.ToInt32(ddlTipoServico3.SelectedValue);
                    //ms.ItemSubServico_id = Convert.ToInt32(ddlItemSubServico.SelectedValue);

                    msd.Salvar(ms);

                    btnNovaTemporadaSubServico.Visible = true;
                    ViewState["NovaTemporadaSubServico"] = 1;
                    ViewState["IdMontaSubServico"] = ms.IdMServico;

                    //btnCalculaServico.Visible = true;
                    btnOpenAddSubServicos.Visible = true;
                    imgRefresh.Visible = true;

                    MostrarMsg("Temporada cadastrada com sucesso, adicione os Sub serviços.");
                }
                else
                {
                    ViewState["NovaTemporadaSubServico"] = 0;
                    txtDataFromSubServico.Text = "";
                    txtDataToSubServico.Text = "";
                    //popularDropTipoServico3();
                    PopulaGridBase(0);
                    PopulaGridSubServAdicionados(0);

                    btnCalculaServico.Visible = false;
                    btnOpenAddSubServicos.Visible = false;
                    imgRefresh.Visible = false;

                    MostrarMsg("Preencha os campos para adicionar uma nova temporada.");
                }

            }
            catch (Exception ex)
            {
                System.Diagnostics.StackTrace trace = new System.Diagnostics.StackTrace(ex, true);
                Log.Save((trace.GetFrame(0).GetMethod().ReflectedType.FullName), ("Linha: " + trace.GetFrame(0).GetFileLineNumber()), ("Column: " + trace.GetFrame(0).GetFileColumnNumber()), ex.Message);

                lblMsgCadSubServico.Text = ex.Message;
            }


            //ViewState["NovaTemporadaSubServico"] = 0;
            //btnCalculaServico.Text = "Calcular e Salvar";
            //txtDataFromSubServico.Text = "";
            //txtDataToSubServico.Text = "";            
            //popularDropTipoServico3();
            //PopulaGridBase(0);
            //PopulaGridSubServAdicionados(0);
            //btnNovaTemporadaSubServico.Visible = false;
        }

        protected void EditarSubServico(object sender, CommandEventArgs e)
        {
            try
            {
                MontaServicoDAL msd = new MontaServicoDAL();
                ServicoCompletoDAL scd = new ServicoCompletoDAL();


                Monta_Servico ms = msd.ObterPorId(Convert.ToInt32(e.CommandArgument));

                txtDataFromSubServico.Text = string.Format("{0:dd/MM/yyyy}", ms.MServico_DataFrom);
                txtDataToSubServico.Text = string.Format("{0:dd/MM/yyyy}", ms.MServico_DataTo);
                //ddlTipoServico3.SelectedValue = ms.Tipo_Id.ToString();
                //ddlItemSubServico.SelectedValue = ms.ItemSubServico_id.ToString();

                //Servico_Completo sc = scd.ObterPorIdTemp(ms.IdMServico);
                //rdoBasesIndexSubServico.SelectedValue = sc.Base_Index.ToString();

                PopulaGridBase(ms.IdMServico);
                PopulaGridSubServAdicionados(ms.IdMServico);

                ViewState["IdMontaSubServico"] = ms.IdMServico;

                btnCalculaServico.Visible = true;
                btnOpenAddSubServicos.Visible = true;
                imgRefresh.Visible = true;
                btnNovaTemporadaSubServico.Visible = true;

                ViewState["NovaTemporadaSubServico"] = 1;
                lblMsgCadSubServico.Text = "";


            }
            catch (Exception ex)
            {
                System.Diagnostics.StackTrace trace = new System.Diagnostics.StackTrace(ex, true);
                Log.Save((trace.GetFrame(0).GetMethod().ReflectedType.FullName), ("Linha: " + trace.GetFrame(0).GetFileLineNumber()), ("Column: " + trace.GetFrame(0).GetFileColumnNumber()), ex.Message);

                lblMsgCadSubServico.Text = ex.Message;
            }
        }

        protected void ExluirSubServico(object sender, CommandEventArgs e)
        {
            try
            {
                int myid = Convert.ToInt32(e.CommandArgument);

                ServicoCompletoDAL scd = new ServicoCompletoDAL();
                MontaServicoDAL msd = new MontaServicoDAL();
                SBaseValorDAL sbv = new SBaseValorDAL();


                foreach (Servico_Completo item in scd.ListarTodosTemporada(myid))
                {
                    scd.Excluir(item);
                }

                foreach (S_Bases_Valor item in sbv.ListarTodos(myid))
                {
                    sbv.Excluir(item);
                }

                Monta_Servico ms = msd.ObterPorId(myid);

                msd.Excluir(ms);

                PopulaGridTemporadasSubServicos(Convert.ToInt32(ViewState["IdSupplierSubServicoPrincipal"]), Convert.ToInt32(Session["IdServico"]));

                ModalPopupExtenderTemporadasSubServico.Show();
            }
            catch (Exception ex)
            {
                System.Diagnostics.StackTrace trace = new System.Diagnostics.StackTrace(ex, true);
                Log.Save((trace.GetFrame(0).GetMethod().ReflectedType.FullName), ("Linha: " + trace.GetFrame(0).GetFileLineNumber()), ("Column: " + trace.GetFrame(0).GetFileColumnNumber()), ex.Message);

                lblMsgCadSubServico.Text = ex.Message;
            }
        }

        protected void btnCopiarTempoSubServ_Click(object sender, EventArgs e)
        {
            try
            {

                MontaServicoDAL msd = new MontaServicoDAL();
                ServicoCompletoDAL scd = new ServicoCompletoDAL();

                Monta_Servico ms = msd.ObterPorId(Convert.ToInt32(ddlTemporadasCadastradasSubServ.SelectedValue));

                Monta_Servico mss = new Monta_Servico();

                mss.MServico_Bulk_Porc_Taxa = ms.MServico_Bulk_Porc_Taxa;
                mss.MServico_Bulk_Porc_Imposto = ms.MServico_Bulk_Porc_Imposto;
                mss.MServico_Bulk_Porc_Comissao = ms.MServico_Bulk_Porc_Comissao;
                mss.MServico_Bulk_Porc_ValorAdicional = ms.MServico_Bulk_Porc_ValorAdicional;
                mss.MServico_PorPessoa = ms.MServico_PorPessoa;
                mss.MServico_DataFrom = Convert.ToDateTime(txtPeriodoFromCopiarTempoSubServ.Text);
                mss.MServico_DataTo = Convert.ToDateTime(txtPeriodoToCopiarTempoSubServ.Text);
                mss.MServico_Obs = ms.MServico_Obs;
                mss.S_id = ms.S_id;
                mss.Tipo_Id = ms.Tipo_Id;
                mss.Tipo_categ_id = ms.Tipo_categ_id;
                mss.ItemSubServico_id = ms.ItemSubServico_id;
                mss.SubItem_id = ms.SubItem_id;

                msd.Salvar(mss);

                List<Servico_Completo> sc = scd.ListarTodosTemporada(Convert.ToInt32(ddlTemporadasCadastradasSubServ.SelectedValue));

                foreach (Servico_Completo item in sc)
                {
                    Servico_Completo scc = new Servico_Completo();

                    scc.IdMServico = item.IdMServico;
                    scc.IdMServico_Temporada = mss.IdMServico;
                    scc.Base_Index = item.Base_Index;
                    scc.Servicos_Id = item.Servicos_Id;
                    scc.ServicoCompleto_de = 0;
                    scc.ServicoCompleto_ate = 0;
                    scc.SubServico = item.SubServico;

                    scd.Salvar(scc);
                }

                PreencheTarifaCopiada(mss.IdMServico);
            }
            catch (Exception ex)
            {
                MostrarMsg(ex.Message);
            }
        }

        protected void PreencheTarifaCopiada(int IdMServico)
        {
            try
            {

                MontaServicoDAL msd = new MontaServicoDAL();
                ServicoCompletoDAL scd = new ServicoCompletoDAL();

                Monta_Servico ms = msd.ObterPorId(IdMServico);

                txtDataFromSubServico.Text = string.Format("{0:dd/MM/yyyy}", ms.MServico_DataFrom);
                txtDataToSubServico.Text = string.Format("{0:dd/MM/yyyy}", ms.MServico_DataTo);

                PopulaGridBase(ms.IdMServico);
                PopulaGridSubServAdicionados(ms.IdMServico);

                ViewState["IdMontaSubServico"] = ms.IdMServico;

                btnCalculaServico.Visible = true;
                btnOpenAddSubServicos.Visible = true;
                imgRefresh.Visible = true;
                btnNovaTemporadaSubServico.Visible = true;

                ViewState["NovaTemporadaSubServico"] = 1;
                lblMsgCadSubServico.Text = "";

                CalculaServico();

            }
            catch (Exception ex)
            {
                MostrarMsg(ex.Message);
            }
        }

        #endregion

        #region Regras MServico Sozinho

        protected void VerificaServico()
        {
            try
            {
                MontaServicoDAL msd = new MontaServicoDAL();

                if (msd.VerificaMS(Convert.ToInt32(ViewState["IdSupplier"]), Convert.ToInt32(Session["IdServico"])))
                {
                    btnVerMServicoCadastrados.Visible = true;
                    btnCopiarMServicoSozinho.Visible = true;
                }
                else
                {
                    btnVerMServicoCadastrados.Visible = false;
                    btnCopiarMServicoSozinho.Visible = false;
                }

            }
            catch (Exception ex)
            {
                System.Diagnostics.StackTrace trace = new System.Diagnostics.StackTrace(ex, true);
                Log.Save((trace.GetFrame(0).GetMethod().ReflectedType.FullName), ("Linha: " + trace.GetFrame(0).GetFileLineNumber()), ("Column: " + trace.GetFrame(0).GetFileColumnNumber()), ex.Message);

                lblMsgCadMServicos.Text = ex.Message;
            }
        }

        protected void txtPorcentagemTaxa_TextChanged(object sender, EventArgs e)
        {

            Utils u = new Utils();

            if (!u.ValidaNumerosInteiros(txtPorcentagemImposto1.Text) || !u.ValidaNumerosInteiros(txtPorcentagemTaxa.Text))
            {
                MostrarMsg("Digite somente números inteiros nas taxas.");
                return;
            }
            else
            {
                lblMsgCadMServicos.Text = "";
            }

            PorcentagemTaxaGridMServico(GridBaseSupplierServicoSozinho);

        }

        protected void txtPorcentagemComissao_TextChanged(object sender, EventArgs e)
        {

            Utils u = new Utils();

            if (!u.ValidaNumerosInteiros(txtComissao.Text))
            {
                MostrarMsg("Digite somente números inteiros na comissao.");
                return;
            }
            else
            {
                lblMsgCadMServicos.Text = "";
            }

            PorcentagemComissaoGridMServico(GridBaseSupplierServicoSozinho);

        }

        protected void btnImgAtualizarTaxas_Click(object sender, ImageClickEventArgs e)
        {
            VerificaTodasTarifas();
            //AdicionaValorTaxas(GridBaseSupplierServicoSozinho);
            txtPorcentagemTaxa_TextChanged(sender, e);
            txtPorcentagemComissao_TextChanged(sender, e);
        }

        protected void ddlMercadoFiltro_Base_SelectedIndexChanged(object sender, EventArgs e)
        {
            PopulaGridServicoSozinho(Convert.ToInt32(rdoBasesIndex.SelectedValue));
        }

        protected void ddlBaseTarifariaFiltro_Base_SelectedIndexChanged(object sender, EventArgs e)
        {
            PopulaGridServicoSozinho(Convert.ToInt32(rdoBasesIndex.SelectedValue));
        }

        protected void ddlMoedaFiltro_Base_SelectedIndexChanged(object sender, EventArgs e)
        {
            PopulaGridServicoSozinho(Convert.ToInt32(rdoBasesIndex.SelectedValue));
        }

        protected void ddlTipoTransporte_SelectedIndexChanged(object sender, EventArgs e)
        {
            PopulaGridServicoSozinho(Convert.ToInt32(rdoBasesIndex.SelectedValue));
        }

        protected void ddlTipoBase_Base_SelectedIndexChanged(object sender, EventArgs e)
        {
            PopulaGridServicoSozinho(Convert.ToInt32(rdoBasesIndex.SelectedValue));
        }

        protected void rdoBasesIndex_SelectedIndexChanged(object sender, EventArgs e)
        {
            PopulaGridServicoSozinho(Convert.ToInt32(rdoBasesIndex.SelectedValue));
        }

        protected void btnFiltroNomeMontaServicoSupplier_Click(object sender, EventArgs e)
        {
            try
            {
                txtObs.Text = "";
                from.Text = "";
                to.Text = "";
                //popularDropTipoServico();
                //popularDropTipoServicoCateg();
                btnAtualizarTarifas.Visible = false;
                btnSalvarTarifas.Text = "Salvar";
                txtCodMServicoSozinho.Text = "";

                PopulaGridServicoSozinho(Convert.ToInt32(rdoBasesIndex.SelectedValue));
                PanelGridMServicoSozinho.Visible = true;
                lblMsgCadMServicos.Text = "";
                PopulaGridMServicosSozinhoCadastrados();
                popularDropPeriodosCopiarMServicoSozinho();
                VerificaServico();
            }
            catch (Exception ex)
            {
                System.Diagnostics.StackTrace trace = new System.Diagnostics.StackTrace(ex, true);
                Log.Save((trace.GetFrame(0).GetMethod().ReflectedType.FullName), ("Linha: " + trace.GetFrame(0).GetFileLineNumber()), ("Column: " + trace.GetFrame(0).GetFileColumnNumber()), ex.Message);

                lblMsgCadMServicos.Text = ex.Message;
            }
        }

        protected void PorcentagemTaxaGridMServico(GridView nome)
        {
            try
            {

                foreach (GridViewRow item in nome.Rows)
                {
                    TextBox txtValorServicoSozinho = (TextBox)item.FindControl("txtValorServicoSozinho");
                    Label lblValorServicoSozinhoTotal = (Label)item.FindControl("lblValorServicoSozinhoTotal");
                    string Bulk = txtValorServicoSozinho.Text;
                    DropDownList ddlTipoCadastro = (DropDownList)item.FindControl("ddlTipoCadastro");

                    if (ddlTipoCadastro.SelectedValue.Equals("0") && Convert.ToInt32(ViewState["opStatusTarifa"]) == 1)
                    {
                        if (!Bulk.Equals(""))
                        {
                            if (!txtPorcentagemTaxa.Equals(""))
                            {
                                double valortarifa = Convert.ToDouble(Bulk);
                                double valortotalComTaxa = (valortarifa * Convert.ToDouble(txtPorcentagemTaxa.Text)) / 100;

                                double d = Convert.ToDouble(valortarifa + valortotalComTaxa);
                                Bulk = d.ToString("N2");

                                double valortarifa2 = Convert.ToDouble(Bulk);
                                double valortotalComImposto = (valortarifa2 * Convert.ToDouble(txtPorcentagemImposto1.Text)) / 100;

                                double d2 = Convert.ToDouble(valortarifa2 + valortotalComImposto);
                                lblValorServicoSozinhoTotal.Text = d2.ToString("N2");
                            }
                            else
                            {
                                Bulk = "";
                            }
                        }
                        else
                        {
                            MostrarMsg("Favor digitar todas as tarifas para salvar.");
                            txtPorcentagemTaxa.Text = "0";
                            txtPorcentagemImposto1.Text = "0";
                        }
                    }
                }

            }
            catch (Exception ex)
            {
                System.Diagnostics.StackTrace trace = new System.Diagnostics.StackTrace(ex, true);
                Log.Save((trace.GetFrame(0).GetMethod().ReflectedType.FullName), ("Linha: " + trace.GetFrame(0).GetFileLineNumber()), ("Column: " + trace.GetFrame(0).GetFileColumnNumber()), ex.Message);

                lblMsgCadMServicos.Text = ex.Message;
            }
        }

        protected void PorcentagemComissaoGridMServico(GridView nome)
        {
            Utils u = new Utils();

            foreach (GridViewRow item in nome.Rows)
            {
                TextBox txtValorServicoSozinho = (TextBox)item.FindControl("txtValorServicoSozinho");
                Label lblValorServicoSozinhoTotal = (Label)item.FindControl("lblValorServicoSozinhoTotal");
                string Bulk = txtValorServicoSozinho.Text;
                DropDownList ddlTipoCadastro = (DropDownList)item.FindControl("ddlTipoCadastro");

                if (ddlTipoCadastro.SelectedValue.Equals("0") && Convert.ToInt32(ViewState["opStatusTarifa"]) == 1)
                {

                    if (!Bulk.Equals(""))
                    {
                        if (!txtComissao.Equals(""))
                        {
                            //PorcentagemTaxaDataList(nome);

                            double valortarifa = Convert.ToDouble(Bulk);
                            double valortotalComComissao = (valortarifa * Convert.ToDouble(txtComissao.Text)) / 100;

                            double d = Convert.ToDouble(Convert.ToDouble(lblValorServicoSozinhoTotal.Text) - valortotalComComissao);
                            lblValorServicoSozinhoTotal.Text = d.ToString("N2");
                        }
                    }
                    else
                    {
                        MostrarMsg("Favor digitar todas as tarifas para salvar.");
                    }
                }

            }

        }

        protected void AdicionaValorTaxas(GridView nome)
        {
            try
            {

                if (chkPercentValorSS.Checked)
                {
                    foreach (GridViewRow item in nome.Rows)
                    {
                        TextBox txtValorServicoSozinho = (TextBox)item.FindControl("txtValorServicoSozinho");
                        Label lblValorServicoSozinhoTotal = (Label)item.FindControl("lblValorServicoSozinhoTotal");
                        string Bulk = txtValorServicoSozinho.Text;

                        if (!Bulk.Equals(""))
                        {
                            double soma = Convert.ToDouble(txtValorServicoSozinho.Text);

                            soma = soma + Convert.ToDouble(txtValorAdicional.Text);

                            txtValorServicoSozinho.Text = soma.ToString("N2");


                            if (!txtPercentValorAdicional.Text.Equals(""))
                            {
                                double percentAdicional = (soma * Convert.ToDouble(txtPercentValorAdicional.Text) / 100) + soma;

                                txtValorServicoSozinho.Text = percentAdicional.ToString("N2");
                            }

                        }
                        else
                        {
                            MostrarMsg("Favor digitar todos os valores para salvar.");
                        }
                    }

                    chkPercentValorSS.Checked = false;

                    if (chkPercentValorSS.Checked)
                    {
                        OpenCalc.ImageUrl = "../../images/Icones/calc2.png";
                    }
                    else
                    {
                        OpenCalc.ImageUrl = "../../images/Icones/calc2S.png";
                    }

                }
            }
            catch (Exception ex)
            {
                System.Diagnostics.StackTrace trace = new System.Diagnostics.StackTrace(ex, true);
                Log.Save((trace.GetFrame(0).GetMethod().ReflectedType.FullName), ("Linha: " + trace.GetFrame(0).GetFileLineNumber()), ("Column: " + trace.GetFrame(0).GetFileColumnNumber()), ex.Message);

                lblMsgCadMServicos.Text = ex.Message;
            }
        }

        protected void EditarMServico(object sender, CommandEventArgs e)
        {
            try
            {
                //LimpaCampos(this.Controls);

                //int myid = Convert.ToInt32(e.CommandArgument);

                string[] param = e.CommandArgument.ToString().Split(',');

                MontaServicoDAL msd = new MontaServicoDAL();
                MontaServicoValoresDAL msvd = new MontaServicoValoresDAL();

                Monta_Servico ms = msd.ObterPorId(Convert.ToInt32(param[0]));

                txtCodMServicoSozinho.Text = ms.IdMServico.ToString();
                //txtSupplier.Text = ms.Supplier.S_nome;
                ddlTipoServico2.SelectedValue = ms.Tipo_Id.ToString();
                popularDropTipoServicoCateg();
                ddlTipoServicoCateg2.SelectedValue = ms.Tipo_categ_id.ToString();
                from.Text = string.Format("{0:dd/MM/yyyy}", ms.MServico_DataFrom);
                to.Text = string.Format("{0:dd/MM/yyyy}", ms.MServico_DataTo);
                txtObs.Text = ms.MServico_Obs;
                txtPorcentagemTaxa.Text = ms.MServico_Bulk_Porc_Taxa.ToString();
                txtPorcentagemImposto1.Text = ms.MServico_Bulk_Porc_Imposto.ToString();
                txtComissao.Text = ms.MServico_Bulk_Porc_Comissao.ToString();
                //txtValorAdicional.Text = ms.MServico_Bulk_Porc_ValorAdicional.ToString();

                SBasesDAL bd = new SBasesDAL();

                S_Bases sb = bd.ObterPorIdSupplier(ms.S_id, Convert.ToInt32(param[1])).First();

                ddlMercadoFiltro_Base.SelectedValue = param[1]; //sb.Mercado_id.ToString();
                ddlBaseTarifariaFiltro_Base.SelectedValue = param[2]; //sb.BaseTarifaria_id.ToString();
                ddlTipoBase_Base.SelectedValue = param[3]; //sb.TipoBase_id.ToString();
                ddlMoedaFiltro_Base.SelectedValue = param[4]; //sb.Moeda_id.ToString();

                Monta_Servico_Valores msv = msvd.ObterPorIdMServico(ms.IdMServico);

                int index = Convert.ToInt32(msv.S_Bases.Base_index);

                PopulaGridServicoSozinho(index);

                btnSalvarTarifas.Text = "Novo";
                btnAtualizarTarifas.Visible = true;
                lblMsgCadMServicos.Text = "";

                ModalPopupExtenderMServicoSozinho.Hide();

                //TabEditarMServicos.ActiveTabIndex = 0;
            }
            catch (Exception ex)
            {
                System.Diagnostics.StackTrace trace = new System.Diagnostics.StackTrace(ex, true);
                Log.Save((trace.GetFrame(0).GetMethod().ReflectedType.FullName), ("Linha: " + trace.GetFrame(0).GetFileLineNumber()), ("Column: " + trace.GetFrame(0).GetFileColumnNumber()), ex.Message);

                lblMsgCadMServicos.Text = ex.Message;
            }
        }

        protected void ExcluirMServico(object sender, CommandEventArgs e)
        {
            try
            {
                int myid = Convert.ToInt32(e.CommandArgument);

                MontaServicoDAL msd = new MontaServicoDAL();

                Monta_Servico ms = msd.ObterPorId(myid);

                msd.Excluir(ms);

                lblMsgCadMServicos.Text = "";
                btnSalvarTarifas.Text = "Salvar";
                //PanelGridMServicoSozinho.Visible = false;
                //LimpaCampos(this.Controls);
                from.Text = "";
                to.Text = "";
                VerificaServico();
                //popularDropTipoServico();
                //popularDropTipoServicoCateg();
                txtPorcentagemTaxa.Text = "0";
                txtPorcentagemImposto1.Text = "0";
                txtComissao.Text = "0";
                txtValorAdicional.Text = "0";
                txtPercentValorAdicional.Text = "0";
                chkPercentValorSS.Checked = false;
                btnAtualizarTarifas.Visible = false;

                PopulaGridServicoSozinho(Convert.ToInt32(rdoBasesIndex.SelectedValue));
                PopulaGridMServicosSozinhoCadastrados();
                popularDropPeriodosCopiarMServicoSozinho();

                ModalPopupExtenderMServicoSozinho.Show();

                MostrarMsg("Registro excluído com sucesso.");
            }
            catch (Exception ex)
            {
                System.Diagnostics.StackTrace trace = new System.Diagnostics.StackTrace(ex, true);
                Log.Save((trace.GetFrame(0).GetMethod().ReflectedType.FullName), ("Linha: " + trace.GetFrame(0).GetFileLineNumber()), ("Column: " + trace.GetFrame(0).GetFileColumnNumber()), ex.Message);

                lblMsgCadMServicos.Text = ex.Message;
            }
        }

        protected void SalvarTarifas(object sender, EventArgs e)
        {
            try
            {

                if (txtCodMServicoSozinho.Text != "")
                {
                    lblMsgCadMServicos.Text = "";
                    btnSalvarTarifas.Text = "Salvar";
                    PanelGridMServicoSozinho.Visible = false;
                    //LimpaCampos(this.Controls);
                    txtSupplierMontaServico.Text = "";
                    txtObs.Text = "";
                    from.Text = "";
                    to.Text = "";
                    //popularDropTipoServico();
                    //popularDropTipoServicoCateg();
                    txtPorcentagemTaxa.Text = "0";
                    txtPorcentagemImposto1.Text = "0";
                    txtComissao.Text = "0";
                    txtValorAdicional.Text = "0";
                    txtPercentValorAdicional.Text = "0";
                    chkPercentValorSS.Checked = false;
                    btnAtualizarTarifas.Visible = false;
                    txtSupplierMontaServico.Focus();
                    return;
                }

                VerificaTodasTarifas();

                txtPorcentagemTaxa_TextChanged(sender, e);
                txtPorcentagemComissao_TextChanged(sender, e);


                Utils u = new Utils();
                MontaServicoDAL msd = new MontaServicoDAL();

                if (ddlTipoServico2.SelectedValue.Equals("0"))
                { MostrarMsg("Favor selecione um serviço."); return; }
                if (ddlTipoServicoCateg2.SelectedValue.Equals("0"))
                { MostrarMsg("Favor selecione uma categoria para o serviço."); return; }

                foreach (GridViewRow item in GridBaseSupplierServicoSozinho.Rows)
                {
                    DropDownList ddlTipoCadastro = (DropDownList)item.FindControl("ddlTipoCadastro");
                    TextBox txtValorServicoSozinho = (TextBox)item.FindControl("txtValorServicoSozinho");
                    string Bulk = txtValorServicoSozinho.Text;
                }

                Monta_Servico ms = new Monta_Servico();

                ms.MServico_Bulk_Porc_Taxa = Convert.ToDecimal(txtPorcentagemTaxa.Text);
                ms.MServico_Bulk_Porc_Imposto = Convert.ToDecimal(txtPorcentagemImposto1.Text);
                ms.MServico_Bulk_Porc_Comissao = Convert.ToDecimal(txtComissao.Text);
                ms.MServico_DataFrom = Convert.ToDateTime(from.Text);
                ms.MServico_DataTo = Convert.ToDateTime(to.Text);
                ms.MServico_Obs = txtObs.Text;
                ms.S_id = Convert.ToInt32(ViewState["IdSupplier"]);
                ms.Tipo_Id = Convert.ToInt32(ddlTipoServico2.SelectedValue);
                ms.Tipo_categ_id = Convert.ToInt32(ddlTipoServicoCateg2.SelectedValue);

                msd.Salvar(ms);

                Servico_Completo sc = new Servico_Completo();
                sc.IdMServico = ms.IdMServico;
                sc.Servicos_Id = Convert.ToInt32(Session["IdServico"]);
                sc.SubServico = false;
                sc.Base_Index = Convert.ToInt32(rdoBasesIndex.SelectedValue);

                ServicoCompletoDAL scd = new ServicoCompletoDAL();
                scd.Salvar(sc);


                foreach (GridViewRow item in GridBaseSupplierServicoSozinho.Rows)
                {
                    Monta_Servico_Valores msv = new Monta_Servico_Valores();

                    string baseID = item.Cells[5].Text;

                    DropDownList ddlStatusTarifa = (DropDownList)item.FindControl("ddlStatusTarifa");

                    TextBox txtValorServicoSozinhoVenda = (TextBox)item.FindControl("txtValorServicoSozinhoVenda");
                    TextBox txtValorServicoSozinho = (TextBox)item.FindControl("txtValorServicoSozinho");
                    Label lblValorServicoSozinhoTotal = (Label)item.FindControl("lblValorServicoSozinhoTotal");
                    string Bulk = txtValorServicoSozinho.Text;

                    msv.IdMServico = ms.IdMServico;

                    if (Convert.ToInt32(ViewState["opStatusTarifa"]) == 1)
                    {
                        if (txtValorServicoSozinho.Text.Equals(""))
                        {
                            msv.MServico_Valores_Bulk_Venda = null;
                            msv.MServico_Valores_Bulk = null;
                            msv.MServico_Valores_Bulk_Total = null;
                            msv.S_mercado_tarifa_status_id = Convert.ToInt32(ddlStatusTarifa.SelectedValue);
                        }
                        else
                        {
                            if (txtValorServicoSozinhoVenda.Text.Equals(""))
                            {
                                msv.MServico_Valores_Bulk_Venda = null;
                            }
                            else
                            {
                                msv.MServico_Valores_Bulk_Venda = Convert.ToDecimal(txtValorServicoSozinhoVenda.Text);
                            }
                            msv.MServico_Valores_Bulk = Convert.ToDecimal(txtValorServicoSozinho.Text);

                            if (lblValorServicoSozinhoTotal.Text.Equals(""))
                            { msv.MServico_Valores_Bulk_Total = null; }
                            else
                            { msv.MServico_Valores_Bulk_Total = Convert.ToDecimal(lblValorServicoSozinhoTotal.Text); }
                        }
                    }
                    else
                    {
                        msv.MServico_Valores_Bulk_Venda = null;
                        msv.MServico_Valores_Bulk = null;
                        msv.MServico_Valores_Bulk_Total = null;

                        int IdStatus = Convert.ToInt32(ConfigurationManager.AppSettings["StatusTarifaServico"]);

                        msv.S_mercado_tarifa_status_id = IdStatus;
                    }

                    msv.Base_id = Convert.ToInt32(baseID);

                    MontaServicoValoresDAL msvd = new MontaServicoValoresDAL();
                    msvd.Salvar(msv);
                }


                MostrarMsg("Registro cadastrado com sucesso.");

                lblMsgCadMServicos.Text = "";
                btnSalvarTarifas.Text = "Salvar";
                from.Text = "";
                to.Text = "";
                VerificaServico();
                //popularDropTipoServico();
                //popularDropTipoServicoCateg();
                txtPorcentagemTaxa.Text = "0";
                txtPorcentagemImposto1.Text = "0";
                txtComissao.Text = "0";
                txtValorAdicional.Text = "0";
                txtPercentValorAdicional.Text = "0";
                chkPercentValorSS.Checked = false;
                btnAtualizarTarifas.Visible = false;

                PopulaGridServicoSozinho(Convert.ToInt32(rdoBasesIndex.SelectedValue));
                PopulaGridMServicosSozinhoCadastrados();
                popularDropPeriodosCopiarMServicoSozinho();

            }
            catch (Exception ex)
            {
                System.Diagnostics.StackTrace trace = new System.Diagnostics.StackTrace(ex, true);
                Log.Save((trace.GetFrame(0).GetMethod().ReflectedType.FullName), ("Linha: " + trace.GetFrame(0).GetFileLineNumber()), ("Column: " + trace.GetFrame(0).GetFileColumnNumber()), ex.Message);

                lblMsgCadMServicos.Text = ex.Message;
            }
        }

        protected void AtualizarTarifas(object sender, EventArgs e)
        {
            try
            {

                Utils u = new Utils();
                MontaServicoDAL msd = new MontaServicoDAL();

                txtPorcentagemTaxa_TextChanged(sender, e);
                txtPorcentagemComissao_TextChanged(sender, e);

                if (ddlTipoServico2.SelectedValue.Equals("0"))
                { MostrarMsg("Favor selecione um serviço."); return; }
                if (ddlTipoServicoCateg2.SelectedValue.Equals("0"))
                { MostrarMsg("Favor selecione uma categoria para o serviço."); return; }

                foreach (GridViewRow item in GridBaseSupplierServicoSozinho.Rows)
                {
                    DropDownList ddlTipoCadastro = (DropDownList)item.FindControl("ddlTipoCadastro");
                    TextBox txtValorServicoSozinhoVenda = (TextBox)item.FindControl("txtValorServicoSozinhoVenda");
                    TextBox txtValorServicoSozinho = (TextBox)item.FindControl("txtValorServicoSozinho");
                    string Bulk = txtValorServicoSozinho.Text;

                    //if (ddlTipoCadastro.SelectedValue.Equals("0"))
                    //{
                    //    if (u.ValidaNumeroComVirgulaInteiro(Bulk))
                    //    {
                    //        MostrarMsg("Favor digite somente números nas tarifas.");
                    //        return;
                    //    }
                    //}
                }

                Monta_Servico ms = new Monta_Servico();

                ms.IdMServico = Convert.ToInt32(txtCodMServicoSozinho.Text);
                ms.MServico_Bulk_Porc_Taxa = Convert.ToDecimal(txtPorcentagemTaxa.Text);
                ms.MServico_Bulk_Porc_Imposto = Convert.ToDecimal(txtPorcentagemImposto1.Text);
                ms.MServico_Bulk_Porc_Comissao = Convert.ToDecimal(txtComissao.Text);
                //ms.MServico_Bulk_Porc_ValorAdicional = Convert.ToDecimal(txtValorAdicional.Text);
                ms.MServico_DataFrom = Convert.ToDateTime(from.Text);
                ms.MServico_DataTo = Convert.ToDateTime(to.Text);
                ms.MServico_Obs = txtObs.Text;
                ms.S_id = Convert.ToInt32(ViewState["IdSupplier"]);
                ms.Tipo_Id = Convert.ToInt32(ddlTipoServico2.SelectedValue);
                ms.Tipo_categ_id = Convert.ToInt32(ddlTipoServicoCateg2.SelectedValue);

                msd.Atualizar(ms);


                foreach (GridViewRow item in GridBaseSupplierServicoSozinho.Rows)
                {
                    Monta_Servico_Valores msv = new Monta_Servico_Valores();

                    string baseID = item.Cells[5].Text;

                    DropDownList ddlStatusTarifa = (DropDownList)item.FindControl("ddlStatusTarifa");
                    DropDownList ddlTipoCadastro = (DropDownList)item.FindControl("ddlTipoCadastro");

                    TextBox txtValorServicoSozinhoVenda = (TextBox)item.FindControl("txtValorServicoSozinhoVenda");
                    TextBox txtValorServicoSozinho = (TextBox)item.FindControl("txtValorServicoSozinho");
                    Label lblValorServicoSozinhoTotal = (Label)item.FindControl("lblValorServicoSozinhoTotal");
                    string Bulk = txtValorServicoSozinho.Text;
                    Label lblIDValores = (Label)item.FindControl("lblIDValores");

                    msv.IdMServicoValores = Convert.ToInt32(lblIDValores.Text);
                    msv.IdMServico = ms.IdMServico;

                    if (ddlTipoCadastro.SelectedValue.Equals("1"))
                    {
                        msv.MServico_Valores_Bulk_Venda = null;
                        msv.MServico_Valores_Bulk = null;
                        msv.MServico_Valores_Bulk_Total = null;
                        msv.S_mercado_tarifa_status_id = Convert.ToInt32(ddlStatusTarifa.SelectedValue);
                    }
                    else
                    {
                        if (txtValorServicoSozinhoVenda.Text.Equals(""))
                        {
                            msv.MServico_Valores_Bulk_Venda = null;
                        }
                        else
                        {
                            msv.MServico_Valores_Bulk_Venda = Convert.ToDecimal(txtValorServicoSozinhoVenda.Text);
                        }
                        msv.MServico_Valores_Bulk = Convert.ToDecimal(txtValorServicoSozinho.Text);

                        if (lblValorServicoSozinhoTotal.Text.Equals(""))
                        { msv.MServico_Valores_Bulk_Total = null; }
                        else
                        { msv.MServico_Valores_Bulk_Total = Convert.ToDecimal(lblValorServicoSozinhoTotal.Text); }
                    }

                    //msv.MServico_Valores_Bulk = Convert.ToDecimal(txtValorServicoSozinho.Text);

                    //if (lblValorServicoSozinhoTotal.Text.Equals(""))
                    //{ msv.MServico_Valores_Bulk_Total = null; }
                    //else
                    //{ msv.MServico_Valores_Bulk_Total = Convert.ToDecimal(lblValorServicoSozinhoTotal.Text); }

                    msv.Base_id = Convert.ToInt32(baseID);

                    MontaServicoValoresDAL msvd = new MontaServicoValoresDAL();
                    msvd.Atualizar(msv);
                }


                MostrarMsg("Registro atualizado com sucesso.");
                PopulaGridMServicosSozinhoCadastrados();
                popularDropPeriodosCopiarMServicoSozinho();
            }
            catch (Exception ex)
            {
                System.Diagnostics.StackTrace trace = new System.Diagnostics.StackTrace(ex, true);
                Log.Save((trace.GetFrame(0).GetMethod().ReflectedType.FullName), ("Linha: " + trace.GetFrame(0).GetFileLineNumber()), ("Column: " + trace.GetFrame(0).GetFileColumnNumber()), ex.Message);


                lblMsgCadMServicos.Text = ex.Message;
            }
        }

        protected void CopiarMServicoSozinho(object sender, EventArgs e)
        {
            AdicionaMontaServicoSozinho();
            MostrarMsg("Temporada copiada com sucesso.");

            PopulaGridServicoSozinho(Convert.ToInt32(rdoBasesIndex.SelectedValue));
            PopulaGridMServicosSozinhoCadastrados();
            popularDropPeriodosCopiarMServicoSozinho();

            ModalPopupExtenderModalCopiarMServicoSozinho.Show();
        }

        protected void AdicionaMontaServicoSozinho()
        {
            try
            {

                MontaServicoDAL msd = new MontaServicoDAL();

                Monta_Servico ms = msd.ObterPorId(Convert.ToInt32(ddlPeriodosMServicoSozinho.SelectedValue));

                Monta_Servico novo = new Monta_Servico();

                novo.MServico_Bulk_Porc_Taxa = ms.MServico_Bulk_Porc_Taxa;
                novo.MServico_Bulk_Porc_Imposto = ms.MServico_Bulk_Porc_Imposto;
                novo.MServico_Bulk_Porc_Comissao = ms.MServico_Bulk_Porc_Comissao;
                //novo.MServico_Bulk_Porc_ValorAdicional = ms.MServico_Bulk_Porc_ValorAdicional;
                novo.MServico_PorPessoa = ms.MServico_PorPessoa;
                novo.MServico_DataFrom = Convert.ToDateTime(txtPeriodoFromCopiarMServSozinho.Text);
                novo.MServico_DataTo = Convert.ToDateTime(txtPeriodoToCopiarMServSozinho.Text);
                novo.MServico_Obs = ms.MServico_Obs;
                novo.S_id = ms.S_id;
                novo.Tipo_Id = ms.Tipo_Id;
                novo.Tipo_categ_id = ms.Tipo_categ_id;

                msd.Salvar(novo);

                AdicionaMontaServicoValoresSozinho(ms.IdMServico, novo.IdMServico, Convert.ToDecimal(ms.MServico_Bulk_Porc_Taxa), Convert.ToDecimal(ms.MServico_Bulk_Porc_Imposto), Convert.ToDecimal(ms.MServico_Bulk_Porc_Comissao));
            }
            catch (Exception ex)
            {
                System.Diagnostics.StackTrace trace = new System.Diagnostics.StackTrace(ex, true);
                Log.Save((trace.GetFrame(0).GetMethod().ReflectedType.FullName), ("Linha: " + trace.GetFrame(0).GetFileLineNumber()), ("Column: " + trace.GetFrame(0).GetFileColumnNumber()), ex.Message);

                lblMsgCadMServicos.Text = ex.Message;
            }
        }

        protected void AdicionaMontaServicoValoresSozinho(int IdMServicoAntigo, int IdMServicoNovo, decimal taxa, decimal imposto, decimal comissao)
        {
            try
            {

                MontaServicoValoresDAL msvd = new MontaServicoValoresDAL();

                List<Monta_Servico_Valores> listaMSV = msvd.ListaTodos(IdMServicoAntigo);

                foreach (Monta_Servico_Valores item in listaMSV)
                {
                    Monta_Servico_Valores novo = new Monta_Servico_Valores();

                    if (item.MServico_Valores_Bulk == null)
                    {
                        novo.MServico_Valores_Bulk_Venda = item.MServico_Valores_Bulk_Venda;
                        novo.MServico_Valores_Bulk = item.MServico_Valores_Bulk;
                        novo.MServico_Valores_Bulk_Total = item.MServico_Valores_Bulk_Total;
                        novo.S_mercado_tarifa_status_id = item.S_mercado_tarifa_status_id;
                    }
                    else
                    {
                        novo.MServico_Valores_Bulk_Venda = item.MServico_Valores_Bulk_Venda;
                        novo.MServico_Valores_Bulk = item.MServico_Valores_Bulk;

                        if (txtPercentCopiarMServicoSozinho.Text.Equals(""))
                        {
                            novo.MServico_Valores_Bulk_Venda = item.MServico_Valores_Bulk_Venda;
                            novo.MServico_Valores_Bulk = item.MServico_Valores_Bulk;
                        }
                        else
                        {
                            novo.MServico_Valores_Bulk_Venda = item.MServico_Valores_Bulk_Venda;

                            double percent = Convert.ToDouble(item.MServico_Valores_Bulk) * Convert.ToDouble(txtPercentCopiarMServicoSozinho.Text) / 100;

                            novo.MServico_Valores_Bulk = Convert.ToDecimal(percent + Convert.ToDouble(item.MServico_Valores_Bulk));

                            double Bulk = Convert.ToDouble(novo.MServico_Valores_Bulk);

                            //if (valoradicional != 0)
                            //{
                            //    double soma = Convert.ToDouble(Bulk);

                            //    double percentAdicional = (soma * Convert.ToDouble(valoradicional) / 100) + soma;

                            //    Bulk = percentAdicional;
                            //}

                            if (!taxa.Equals(""))
                            {

                                double valortarifa = Convert.ToDouble(Bulk);
                                double valortotalComTaxa = (valortarifa * Convert.ToDouble(taxa)) / 100;

                                double d = Convert.ToDouble(valortarifa + valortotalComTaxa);
                                Bulk = d;

                                double valortarifa2 = Convert.ToDouble(Bulk);
                                double valortotalComImposto = (valortarifa2 * Convert.ToDouble(imposto)) / 100;

                                double d2 = Convert.ToDouble(valortarifa2 + valortotalComImposto);

                                novo.MServico_Valores_Bulk_Total = Convert.ToDecimal(d2);

                                if (comissao != 0)
                                {
                                    double valortarifaCom = Convert.ToDouble(Bulk);
                                    double valortotalComComissao = (valortarifa * Convert.ToDouble(comissao)) / 100;

                                    double dCom = Convert.ToDouble(Convert.ToDouble(Bulk) - valortotalComComissao);

                                    novo.MServico_Valores_Bulk_Total = Convert.ToDecimal(dCom);
                                }

                            }


                        }
                    }

                    novo.IdMServico = IdMServicoNovo;
                    novo.Base_id = item.Base_id;

                    msvd.Salvar(novo);
                }

                Servico_Completo sc = new Servico_Completo();
                sc.IdMServico = IdMServicoNovo;
                sc.Servicos_Id = Convert.ToInt32(Session["IdServico"]);
                sc.SubServico = false;
                sc.Base_Index = Convert.ToInt32(rdoBasesIndex.SelectedValue);

                ServicoCompletoDAL scd = new ServicoCompletoDAL();
                scd.Salvar(sc);

                txtPeriodoFromCopiarMServSozinho.Text = "";
                txtPeriodoToCopiarMServSozinho.Text = "";
                txtPercentCopiarMServicoSozinho.Text = "";

                MostrarMsg("Tarifa copiada com sucesso.");

            }
            catch (Exception ex)
            {
                System.Diagnostics.StackTrace trace = new System.Diagnostics.StackTrace(ex, true);
                Log.Save((trace.GetFrame(0).GetMethod().ReflectedType.FullName), ("Linha: " + trace.GetFrame(0).GetFileLineNumber()), ("Column: " + trace.GetFrame(0).GetFileColumnNumber()), ex.Message);

                lblMsgCadMServicos.Text = ex.Message;
            }
        }

        protected void chkPercentValorSS_CheckedChanged(object sender, EventArgs e)
        {
            if (chkPercentValorSS.Checked)
            {
                OpenCalc.ImageUrl = "../../images/Icones/calc2.png";
            }
            else
            {
                OpenCalc.ImageUrl = "../../images/Icones/calc2S.png";
            }

            ModalPopupExtenderAddCategoria.Show();
        }

        protected void MudaTipoCadastroServSoz(object sender, EventArgs e)
        {
            try
            {

                DropDownList ddl = (DropDownList)sender;
                GridViewRow row = (GridViewRow)ddl.Parent.Parent;
                int idx = row.RowIndex;

                foreach (GridViewRow item in GridBaseSupplierServicoSozinho.Rows)
                {

                    TextBox txtValorServicoSozinhoVenda = (TextBox)item.FindControl("txtValorServicoSozinhoVenda");
                    TextBox txtValorServicoSozinho = (TextBox)item.FindControl("txtValorServicoSozinho");
                    DropDownList ddlTipoCadastro = (DropDownList)item.FindControl("ddlTipoCadastro");
                    DropDownList ddlStatusTarifa = (DropDownList)item.FindControl("ddlStatusTarifa");
                    Label lblValorServicoSozinhoTotal = (Label)item.FindControl("lblValorServicoSozinhoTotal");

                    int IdBase = Convert.ToInt32(item.Cells[5].Text);

                    if (item.RowIndex == idx)
                    {
                        if (ddlTipoCadastro.SelectedItem.ToString() == "Status")
                        {
                            SMercadoTarifaStatusDAL smt = new SMercadoTarifaStatusDAL();

                            PopulaDropStatusTarifa(ddlStatusTarifa);

                            txtValorServicoSozinho.Visible = false;
                            txtValorServicoSozinhoVenda.Visible = false;

                            txtValorServicoSozinhoVenda.Text = "";
                            txtValorServicoSozinho.Text = "";
                            lblValorServicoSozinhoTotal.Text = "";

                            ddlStatusTarifa.Visible = true;
                            lblValorServicoSozinhoTotal.Visible = false;
                        }
                        else
                        {
                            txtValorServicoSozinhoVenda.Visible = true;
                            txtValorServicoSozinho.Visible = true;
                            lblValorServicoSozinhoTotal.Visible = true;
                            ddlStatusTarifa.Visible = false;
                        }
                    }

                }

            }
            catch (Exception ex)
            {
                System.Diagnostics.StackTrace trace = new System.Diagnostics.StackTrace(ex, true);
                Log.Save((trace.GetFrame(0).GetMethod().ReflectedType.FullName), ("Linha: " + trace.GetFrame(0).GetFileLineNumber()), ("Column: " + trace.GetFrame(0).GetFileColumnNumber()), ex.Message);

                MostrarMsg(ex.Message);
            }
        }

        protected void txtValorServicoSozinho_TextChanged(object sender, EventArgs e)
        {
            TextBox txtValor = (TextBox)sender;
            GridViewRow row = (GridViewRow)txtValor.Parent.Parent;
            int idx = row.RowIndex;

            foreach (GridViewRow item in GridBaseSupplierServicoSozinho.Rows)
            {
                TextBox txtValorServicoSozinho = (TextBox)item.FindControl("txtValorServicoSozinho");
                Label lblValorServicoSozinhoTotal = (Label)item.FindControl("lblValorServicoSozinhoTotal");
                string Bulk = txtValorServicoSozinho.Text;

                if (item.RowIndex == idx)
                {
                    if (chkPercentValorSS.Checked)
                    {
                        double soma = Convert.ToDouble(txtValorServicoSozinho.Text);

                        soma = soma + Convert.ToDouble(txtValorAdicional.Text);

                        txtValorServicoSozinho.Text = soma.ToString("N2");

                        if (!txtPercentValorAdicional.Text.Equals(""))
                        {
                            double percentAdicional = (soma * Convert.ToDouble(txtPercentValorAdicional.Text) / 100) + soma;

                            txtValorServicoSozinho.Text = percentAdicional.ToString("N2");
                        }
                    }
                }

                if (item.RowIndex == idx + 1)
                {
                    txtValorServicoSozinho.Focus();
                }

            }
        }

        protected void PopulaDropStatusTarifa(DropDownList ddlStatusTarifa)
        {
            try
            {
                SMercadoTarifaStatusDAL smt = new SMercadoTarifaStatusDAL();

                ddlStatusTarifa.DataSource = smt.ListarTodos();
                ddlStatusTarifa.DataValueField = "S_mercado_tarifa_status_id";
                ddlStatusTarifa.DataTextField = "S_mercado_tarifa_status_nome";
                ddlStatusTarifa.DataBind();

                ddlStatusTarifa.Items.Insert(0, new ListItem("Selecione", "0"));
            }
            catch (Exception ex)
            {
                System.Diagnostics.StackTrace trace = new System.Diagnostics.StackTrace(ex, true);
                Log.Save((trace.GetFrame(0).GetMethod().ReflectedType.FullName), ("Linha: " + trace.GetFrame(0).GetFileLineNumber()), ("Column: " + trace.GetFrame(0).GetFileColumnNumber()), ex.Message);

                MostrarMsg(ex.Message);
            }
        }

        protected void VerificaTodasTarifas()
        {
            try
            {
                ViewState["opStatusTarifa"] = 0;

                foreach (GridViewRow item in GridBaseSupplierServicoSozinho.Rows)
                {
                    TextBox txtValorServicoSozinho = (TextBox)item.FindControl("txtValorServicoSozinho");

                    if (!txtValorServicoSozinho.Text.Equals(""))
                    {
                        ViewState["opStatusTarifa"] = 1;
                        break;
                    }
                }
            }
            catch (Exception ex)
            {
                MostrarMsg(ex.Message);
            }
        }

        #endregion

        #region Regras Serv Por Supp

        protected void btnFiltroSupplierServPorSupp_Click(object sender, EventArgs e)
        {
            try
            {
                SupplierDAL sd = new SupplierDAL();

                Supplier s = sd.ObterSupplierPorNome(txtSupplierServPorSupp.Text);

                PopulaGridServPorSupp(sd.ObterSupplierPorNome(txtSupplierServPorSupp.Text).S_id);

                btnReportFiltroSupplierServPorSupp.Visible = true;
                ViewState["IdSupplierReport"] = s.S_id;

            }
            catch (Exception ex)
            {
                System.Diagnostics.StackTrace trace = new System.Diagnostics.StackTrace(ex, true);
                Log.Save((trace.GetFrame(0).GetMethod().ReflectedType.FullName), ("Linha: " + trace.GetFrame(0).GetFileLineNumber()), ("Column: " + trace.GetFrame(0).GetFileColumnNumber()), ex.Message);

                lblMsgCadServPorSupp.Text = ex.Message;
            }
        }

        protected void btnReportFiltroSupplierServPorSupp_Click(object sender, EventArgs e)
        {
            try
            {

                string NomeEmpresa = ConfigurationManager.AppSettings["NomeEmpresa"];
                string EnderecoEmpresa = ConfigurationManager.AppSettings["EnderecoEmpresa"];
                string ContatoEmpresa = ConfigurationManager.AppSettings["ContatoEmpresa"];

                DSFiltroSupplierServico ds = new DSFiltroSupplierServico();

                DataTable dt = ds.Tables["FILTROSUPPLIER"];

                string[] pars = ConfigurationManager.ConnectionStrings["NewTierraEntities"].ToString().Split('\"');
                SqlConnection Con = new SqlConnection(pars[1]);
                string sql;

                Con.Open();

                sql = "SELECT S_Servicos.Servicos_Nome, Monta_Servico.MServico_DataFrom, Monta_Servico.MServico_DataTo, S_Bases.Base_de, S_Bases.Base_ate, ";
                sql = sql + "Monta_Servico_Valores.MServico_Valores_Bulk_Total, S_Mercado_Tarifa_Status.S_mercado_tarifa_status_nome, Monta_Servico.S_id ";
                sql = sql + "FROM S_Servicos INNER JOIN Servico_Completo ON S_Servicos.Servicos_Id = Servico_Completo.Servicos_Id INNER JOIN Monta_Servico ON ";
                sql = sql + "Servico_Completo.IdMServico = Monta_Servico.IdMServico INNER JOIN Monta_Servico_Valores ON Monta_Servico.IdMServico = Monta_Servico_Valores.IdMServico INNER JOIN ";
                sql = sql + "S_Bases ON Monta_Servico_Valores.Base_id = S_Bases.Base_id LEFT OUTER JOIN S_Mercado_Tarifa_Status ON Monta_Servico_Valores.S_mercado_tarifa_status_id = S_Mercado_Tarifa_Status.S_mercado_tarifa_status_id ";
                sql = sql + "WHERE Monta_Servico.S_id = " + Convert.ToInt32(ViewState["IdSupplierReport"]);

                SqlCommand cmd = new SqlCommand(sql, Con);
                SqlDataReader reader = cmd.ExecuteReader();

                while (reader.Read())
                {
                    DataRow dr = dt.NewRow();

                    dr["Servico_nome"] = reader["Servicos_Nome"].ToString();
                    dr["DataFrom"] = Convert.ToDateTime(reader["MServico_DataFrom"]);
                    dr["DataTo"] = Convert.ToDateTime(reader["MServico_DataTo"]);
                    dr["Base_de"] = Convert.ToInt32(reader["Base_de"]);
                    dr["Base_ate"] = Convert.ToInt32(reader["Base_ate"]);
                    dr["BulkTotal"] = reader["MServico_Valores_Bulk_Total"];
                    dr["StatusNome"] = reader["S_mercado_tarifa_status_nome"].ToString();

                    dt.Rows.Add(dr);
                }

                RptFiltroSupplierServico rpt = new RptFiltroSupplierServico();

                CrystalDecisions.CrystalReports.Engine.TextObject ObjNomeEmpresa = rpt.ReportDefinition.Sections[1].ReportObjects["NomeEmpresa"] as TextObject;
                CrystalDecisions.CrystalReports.Engine.TextObject ObjEnderecoEmpresa = rpt.ReportDefinition.Sections[1].ReportObjects["EnderecoEmpresa"] as TextObject;
                CrystalDecisions.CrystalReports.Engine.TextObject ObjContatoEmpresa = rpt.ReportDefinition.Sections[1].ReportObjects["ContatoEmpresa"] as TextObject;
                ObjNomeEmpresa.Text = NomeEmpresa;
                ObjEnderecoEmpresa.Text = EnderecoEmpresa;
                ObjContatoEmpresa.Text = ContatoEmpresa;

                rpt.SetDataSource(dt);

                rpt.ExportToHttpResponse(ExportFormatType.PortableDocFormat, Response, true, "Serviços por supplier");

                Con.Close();
            }
            catch (Exception ex)
            {
                System.Diagnostics.StackTrace trace = new System.Diagnostics.StackTrace(ex, true);
                Log.Save((trace.GetFrame(0).GetMethod().ReflectedType.FullName), ("Linha: " + trace.GetFrame(0).GetFileLineNumber()), ("Column: " + trace.GetFrame(0).GetFileColumnNumber()), ex.Message);

                MostrarMsg(ex.Message);
            }
        }

        #endregion

        #region Regras Holidays

        protected void PopulaHolidays()
        {
            try
            {
                HolidaysDAL hd = new HolidaysDAL();

                Holidays h = hd.ObterPorIdServ(Convert.ToInt32(Session["IdServico"]));

                if (h != null)
                {
                    ViewState["IdHolidays"] = h.Holidays_id;

                    PopulaGridHolidaysDates(h.Holidays_id);
                    PopulaGridHolidaysPeriodos(h.Holidays_id);

                    chkSeg.Checked = Convert.ToBoolean(h.Holidays_seg);
                    chkTer.Checked = Convert.ToBoolean(h.Holidays_ter);
                    chkQua.Checked = Convert.ToBoolean(h.Holidays_qua);
                    chkQui.Checked = Convert.ToBoolean(h.Holidays_qui);
                    chkSex.Checked = Convert.ToBoolean(h.Holidays_sex);
                    chkSab.Checked = Convert.ToBoolean(h.Holidays_sab);
                    chkDom.Checked = Convert.ToBoolean(h.Holidays_dom);

                    txtRemarkHolidays.Text = h.Holidays_remarks;

                    lblHolidayServicoNome.Text = Session["nomeServico"].ToString();
                }
                else
                {
                    Holidays hy = new Holidays();

                    hy.Servicos_Id = Convert.ToInt32(Session["IdServico"]);
                    hy.Holidays_seg = false;
                    hy.Holidays_ter = false;
                    hy.Holidays_qua = false;
                    hy.Holidays_qui = false;
                    hy.Holidays_sex = false;
                    hy.Holidays_sab = false;
                    hy.Holidays_dom = false;

                    hd.Salvar(hy);

                    ViewState["IdHolidays"] = hy.Holidays_id;

                    chkSeg.Checked = Convert.ToBoolean(hy.Holidays_seg);
                    chkTer.Checked = Convert.ToBoolean(hy.Holidays_ter);
                    chkQua.Checked = Convert.ToBoolean(hy.Holidays_qua);
                    chkQui.Checked = Convert.ToBoolean(hy.Holidays_qui);
                    chkSex.Checked = Convert.ToBoolean(hy.Holidays_sex);
                    chkSab.Checked = Convert.ToBoolean(hy.Holidays_sab);
                    chkDom.Checked = Convert.ToBoolean(hy.Holidays_dom);

                    txtRemarkHolidays.Text = hy.Holidays_remarks;

                    PopulaGridHolidaysDates(hy.Holidays_id);
                    PopulaGridHolidaysPeriodos(hy.Holidays_id);
                }

            }
            catch (Exception ex)
            {
                System.Diagnostics.StackTrace trace = new System.Diagnostics.StackTrace(ex, true);
                Log.Save((trace.GetFrame(0).GetMethod().ReflectedType.FullName), ("Linha: " + trace.GetFrame(0).GetFileLineNumber()), ("Column: " + trace.GetFrame(0).GetFileColumnNumber()), ex.Message);

                lblMsgCadServicos.Text = ex.Message;
            }
        }

        protected void PopulaGridHolidaysDates(int IdHol)
        {
            try
            {
                HolidaysDatesDAL hd = new HolidaysDatesDAL();

                GridHolidaysDates.DataSource = hd.ObterPorIdHolidays(IdHol);
                GridHolidaysDates.DataBind();

            }
            catch (Exception ex)
            {
                System.Diagnostics.StackTrace trace = new System.Diagnostics.StackTrace(ex, true);
                Log.Save((trace.GetFrame(0).GetMethod().ReflectedType.FullName), ("Linha: " + trace.GetFrame(0).GetFileLineNumber()), ("Column: " + trace.GetFrame(0).GetFileColumnNumber()), ex.Message);

                lblMsgCadServicos.Text = ex.Message;
            }
        }

        protected void PopulaGridHolidaysPeriodos(int IdHol)
        {
            try
            {
                HolidaysPeriodosDAL hd = new HolidaysPeriodosDAL();

                GridHolidaysPeriods.DataSource = hd.ObterPorIdHolidays(IdHol);
                GridHolidaysPeriods.DataBind();

            }
            catch (Exception ex)
            {
                System.Diagnostics.StackTrace trace = new System.Diagnostics.StackTrace(ex, true);
                Log.Save((trace.GetFrame(0).GetMethod().ReflectedType.FullName), ("Linha: " + trace.GetFrame(0).GetFileLineNumber()), ("Column: " + trace.GetFrame(0).GetFileColumnNumber()), ex.Message);

                lblMsgCadServicos.Text = ex.Message;
            }
        }

        protected void btnSalvarDate_Command(object sender, CommandEventArgs e)
        {
            try
            {
                HolidaysDatesDAL hdd = new HolidaysDatesDAL();

                Holidays_Dates hd = new Holidays_Dates();

                if (GridHolidaysDates.Rows.Count == 0)
                {
                    TextBox txtdataFooter = (TextBox)GridHolidaysDates.Controls[0].Controls[0].FindControl("txtdataFooter");
                    hd.Holidays_Dates_data = Convert.ToDateTime(txtdataFooter.Text);
                    hd.Holidays_id = Convert.ToInt32(ViewState["IdHolidays"]);

                    hdd.Salvar(hd);
                }
                else
                {
                    TextBox txtdata = ((TextBox)GridHolidaysDates.FooterRow.FindControl("txtdata"));
                    hd.Holidays_Dates_data = Convert.ToDateTime(txtdata.Text);
                    hd.Holidays_id = Convert.ToInt32(ViewState["IdHolidays"]);

                    hdd.Salvar(hd);
                }


                PopulaGridHolidaysDates(Convert.ToInt32(ViewState["IdHolidays"]));
                ModalPopupExtenderHolidays.Show();
            }
            catch (Exception ex)
            {
                System.Diagnostics.StackTrace trace = new System.Diagnostics.StackTrace(ex, true);
                Log.Save((trace.GetFrame(0).GetMethod().ReflectedType.FullName), ("Linha: " + trace.GetFrame(0).GetFileLineNumber()), ("Column: " + trace.GetFrame(0).GetFileColumnNumber()), ex.Message);

                lblMsgCadServicos.Text = ex.Message;
            }
        }

        protected void ExluirHolidaysDates_Command(object sender, CommandEventArgs e)
        {
            try
            {

                HolidaysDatesDAL hdd = new HolidaysDatesDAL();

                Holidays_Dates hd = hdd.ObterPorId(Convert.ToInt32(e.CommandArgument));

                hdd.Excluir(hd);

                PopulaGridHolidaysDates(Convert.ToInt32(ViewState["IdHolidays"]));
                ModalPopupExtenderHolidays.Show();

            }
            catch (Exception ex)
            {
                System.Diagnostics.StackTrace trace = new System.Diagnostics.StackTrace(ex, true);
                Log.Save((trace.GetFrame(0).GetMethod().ReflectedType.FullName), ("Linha: " + trace.GetFrame(0).GetFileLineNumber()), ("Column: " + trace.GetFrame(0).GetFileColumnNumber()), ex.Message);

                lblMsgCadServicos.Text = ex.Message;
            }
        }

        protected void btnSalvarPeriods_Command(object sender, CommandEventArgs e)
        {
            try
            {
                HolidaysPeriodosDAL hdd = new HolidaysPeriodosDAL();

                Holidays_Periodo hd = new Holidays_Periodo();

                if (GridHolidaysPeriods.Rows.Count == 0)
                {
                    TextBox txtdataFromFooter = (TextBox)GridHolidaysPeriods.Controls[0].Controls[0].FindControl("txtdataFromFooter");
                    TextBox txtdataToFooter = (TextBox)GridHolidaysPeriods.Controls[0].Controls[0].FindControl("txtdataToFooter");

                    hd.HoliDays_Periodo_from = Convert.ToDateTime(txtdataFromFooter.Text);
                    hd.HoliDays_Periodo_to = Convert.ToDateTime(txtdataToFooter.Text);
                    hd.Holidays_id = Convert.ToInt32(ViewState["IdHolidays"]);

                    hdd.Salvar(hd);
                }
                else
                {
                    TextBox txtdataFrom = ((TextBox)GridHolidaysPeriods.FooterRow.FindControl("txtdataFrom"));
                    TextBox txtdataTo = ((TextBox)GridHolidaysPeriods.FooterRow.FindControl("txtdataTo"));

                    hd.HoliDays_Periodo_from = Convert.ToDateTime(txtdataFrom.Text);
                    hd.HoliDays_Periodo_to = Convert.ToDateTime(txtdataTo.Text);
                    hd.Holidays_id = Convert.ToInt32(ViewState["IdHolidays"]);

                    hdd.Salvar(hd);
                }

                PopulaGridHolidaysPeriodos(Convert.ToInt32(ViewState["IdHolidays"]));
                ModalPopupExtenderHolidays.Show();
            }
            catch (Exception ex)
            {
                System.Diagnostics.StackTrace trace = new System.Diagnostics.StackTrace(ex, true);
                Log.Save((trace.GetFrame(0).GetMethod().ReflectedType.FullName), ("Linha: " + trace.GetFrame(0).GetFileLineNumber()), ("Column: " + trace.GetFrame(0).GetFileColumnNumber()), ex.Message);

                lblMsgCadServicos.Text = ex.Message;
            }
        }

        protected void ExluirHolidaysPeriodo_Command(object sender, CommandEventArgs e)
        {
            try
            {

                HolidaysPeriodosDAL hdd = new HolidaysPeriodosDAL();

                Holidays_Periodo hd = hdd.ObterPorId(Convert.ToInt32(e.CommandArgument));

                hdd.Excluir(hd);

                PopulaGridHolidaysPeriodos(Convert.ToInt32(ViewState["IdHolidays"]));
                ModalPopupExtenderHolidays.Show();
            }
            catch (Exception ex)
            {
                System.Diagnostics.StackTrace trace = new System.Diagnostics.StackTrace(ex, true);
                Log.Save((trace.GetFrame(0).GetMethod().ReflectedType.FullName), ("Linha: " + trace.GetFrame(0).GetFileLineNumber()), ("Column: " + trace.GetFrame(0).GetFileColumnNumber()), ex.Message);

                lblMsgCadServicos.Text = ex.Message;
            }
        }

        protected void btnSalvarHolidays_Click(object sender, EventArgs e)
        {
            try
            {

                Holidays h = new Holidays();

                h.Holidays_id = Convert.ToInt32(ViewState["IdHolidays"]);
                h.Holidays_remarks = txtRemarkHolidays.Text;

                h.Holidays_seg = chkSeg.Checked;
                h.Holidays_ter = chkTer.Checked;
                h.Holidays_qua = chkQua.Checked;
                h.Holidays_qui = chkQui.Checked;
                h.Holidays_sex = chkSex.Checked;
                h.Holidays_sab = chkSab.Checked;
                h.Holidays_dom = chkDom.Checked;

                HolidaysDAL hd = new HolidaysDAL();

                hd.Atualizar(h);

                MostrarMsg("Registro cadastrado com sucesso.");
                ModalPopupExtenderHolidays.Show();
            }
            catch (Exception ex)
            {
                MostrarMsg(ex.Message);
            }
        }

        #endregion

        #region Regras

        [WebMethod]
        protected void btnImgFilter_Click(object sender, ImageClickEventArgs e)
        {
            if (displayFiltro.Equals("none"))
            {

                displayFiltro = "block";
            }
            else
            {
                PopularDDTipoServicoFiltro();
                PopularDDTipoServicoCategFiltro();
                PopularDDStatusFiltro();

                displayFiltro = "none";
            }
        }

        protected void VoltarMenu(object sender, EventArgs e)
        {
            Response.Redirect("~/Pages/Index.aspx");
        }

        [WebMethod]
        public static List<string> SearchServicos(string prefixText)
        {
            using (NewTierraEntities Con = new NewTierraEntities())
            {
                int idStatus = Convert.ToInt32(HttpContext.Current.Session["IDsFiltroStatusServicos"]);
                int idTipoServico = Convert.ToInt32(HttpContext.Current.Session["IDsFiltroTipoServicos"]);
                int idTipoCategServico = Convert.ToInt32(HttpContext.Current.Session["IDsFiltroTipoCategServicos"]);
                int idCidade = Convert.ToInt32(HttpContext.Current.Session["IDsFiltroCidadeServico"]);

                List<S_Servicos> s = new List<S_Servicos>();

                if (idTipoServico > 0 && idStatus > 0 && idTipoCategServico > 0 && idCidade > 0)
                {
                    if (prefixText.Equals("*"))
                    {
                        s = Con.S_Servicos.Where(p => p.Tipo_Id == idTipoServico
                                            && p.STATUS_id == idStatus
                                            && p.Tipo_categ_id == idTipoCategServico
                                            && p.Cid_Id == idCidade).OrderBy(p => p.Servicos_Nome).ToList();
                    }
                    else
                    {
                        s = Con.S_Servicos.Where(p => p.Servicos_Nome.Contains(prefixText)
                                            && p.Tipo_Id == idTipoServico
                                            && p.STATUS_id == idStatus
                                            && p.Tipo_categ_id == idTipoCategServico
                                            && p.Cid_Id == idCidade).OrderBy(p => p.Servicos_Nome).ToList();
                    }
                }
                else if (idCidade > 0 && idTipoServico > 0 && idTipoCategServico > 0)
                {
                    if (prefixText.Equals("*"))
                    {
                        s = Con.S_Servicos.Where(p => p.Tipo_Id == idTipoServico && p.Cid_Id == idCidade && p.Tipo_categ_id == idTipoCategServico).OrderBy(p => p.Servicos_Nome).ToList();
                    }
                    else
                    {
                        s = Con.S_Servicos.Where(p => p.Servicos_Nome.Contains(prefixText) && p.Tipo_Id == idTipoServico && p.Cid_Id == idCidade && p.Tipo_categ_id == idTipoCategServico).OrderBy(p => p.Servicos_Nome).ToList();
                    }
                }
                else if (idTipoServico > 0 && idStatus > 0)
                {
                    if (prefixText.Equals("*"))
                    {
                        s = Con.S_Servicos.Where(p => p.Tipo_Id == idTipoServico && p.STATUS_id == idStatus).OrderBy(p => p.Servicos_Nome).ToList();
                    }
                    else
                    {
                        s = Con.S_Servicos.Where(p => p.Servicos_Nome.Contains(prefixText) && p.Tipo_Id == idTipoServico && p.STATUS_id == idStatus).OrderBy(p => p.Servicos_Nome).ToList();
                    }
                }
                else if (idTipoServico > 0 && idCidade > 0)
                {
                    if (prefixText.Equals("*"))
                    {
                        s = Con.S_Servicos.Where(p => p.Tipo_Id == idTipoServico && p.Cid_Id == idCidade).OrderBy(p => p.Servicos_Nome).ToList();
                    }
                    else
                    {
                        s = Con.S_Servicos.Where(p => p.Servicos_Nome.Contains(prefixText) && p.Tipo_Id == idTipoServico && p.Cid_Id == idCidade).OrderBy(p => p.Servicos_Nome).ToList();
                    }
                }
                else if (idStatus > 0 && idCidade > 0)
                {
                    if (prefixText.Equals("*"))
                    {
                        s = Con.S_Servicos.Where(p => p.STATUS_id == idStatus && p.Cid_Id == idCidade).OrderBy(p => p.Servicos_Nome).ToList();
                    }
                    else
                    {
                        s = Con.S_Servicos.Where(p => p.Servicos_Nome.Contains(prefixText) && p.STATUS_id == idStatus && p.Cid_Id == idCidade).OrderBy(p => p.Servicos_Nome).ToList();
                    }
                }
                else if (idTipoServico > 0)
                {
                    if (prefixText.Equals("*"))
                    {
                        s = Con.S_Servicos.Where(p => p.Tipo_Id == idTipoServico).OrderBy(z => z.Servicos_Nome).ToList();
                    }
                    else
                    {
                        s = Con.S_Servicos.Where(p => p.Servicos_Nome.Contains(prefixText) && p.Tipo_Id == idTipoServico).OrderBy(z => z.Servicos_Nome).ToList();
                    }
                }
                else if (idCidade > 0)
                {
                    if (prefixText.Equals("*"))
                    {
                        s = Con.S_Servicos.Where(p => p.Cid_Id == idCidade).OrderBy(z => z.Servicos_Nome).ToList();
                    }
                    else
                    {
                        s = Con.S_Servicos.Where(p => p.Servicos_Nome.Contains(prefixText) && p.Cid_Id == idCidade).OrderBy(z => z.Servicos_Nome).ToList();
                    }
                }
                else if (idStatus > 0)
                {
                    if (prefixText.Equals("*"))
                    {
                        s = Con.S_Servicos.Where(p => p.STATUS_id == idStatus).OrderBy(z => z.Servicos_Nome).ToList();
                    }
                    else
                    {
                        s = Con.S_Servicos.Where(p => p.Servicos_Nome.Contains(prefixText) && p.STATUS_id == idStatus).OrderBy(z => z.Servicos_Nome).ToList();
                    }
                }
                else
                {
                    if (prefixText.Equals("*"))
                    {
                        s = Con.S_Servicos.OrderBy(z => z.Servicos_Nome).ToList();
                    }
                    else
                    {
                        s = Con.S_Servicos.Where(p => p.Servicos_Nome.Contains(prefixText)).OrderBy(z => z.Servicos_Nome).ToList();
                    }
                }



                List<string> lista = new List<string>();

                if (s.Count == 0)
                {
                    lista.Add("Não existe serviço cadastrado com esse nome.");

                    return lista;
                }

                foreach (S_Servicos p in s)
                {
                    lista.Add(p.Servicos_Nome + " ° " + p.Cidade.CID_nome);
                }

                return lista;
            }
        }

        [WebMethod]
        public static List<string> SearchSuppliers(string prefixText, int count)
        {
            try
            {
                SupplierDAL s = new SupplierDAL();

                List<Supplier> supp = s.ListarTodos(prefixText, 1);

                List<string> lista = new List<string>();

                if (supp.Count == 0)
                {
                    lista.Add("Não existe supplier cadastrado com esse nome.");

                    return lista;
                }

                foreach (Supplier p in supp)
                {
                    lista.Add(p.S_nome);
                }

                return lista;
            }
            catch
            {
                throw;
            }
        }

        protected void DDStatusFiltro_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (DDStatusFiltro.SelectedValue.Equals("0"))
            {
                Session["IDsFiltroStatusServicos"] = 0;
            }
            else
            {
                Session["IDsFiltroStatusServicos"] = DDStatusFiltro.SelectedValue;
            }
        }

        protected void DDTipoServicoFiltro_SelectedIndexChanged(object sender, EventArgs e)
        {
            PopularDDTipoServicoCategFiltro();

            if (DDTipoServicoFiltro.SelectedValue.Equals("0"))
            {
                Session["IDsFiltroTipoServicos"] = 0;
            }
            else
            {
                Session["IDsFiltroTipoServicos"] = DDTipoServicoFiltro.SelectedValue;
            }
        }

        protected void DDCidadeServicoFiltro_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (ddlCidadeServicoFiltro.SelectedValue.Equals("0"))
            {
                Session["IDsFiltroCidadeServico"] = 0;
            }
            else
            {
                Session["IDsFiltroCidadeServico"] = ddlCidadeServicoFiltro.SelectedValue;
            }
        }

        protected void DDTipoServicoCategFiltro_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (DDTipoServicoFiltro.SelectedValue.Equals("0"))
            {
                Session["IDsFiltroTipoCategServicos"] = 0;
            }
            else
            {
                Session["IDsFiltroTipoCategServicos"] = ddlTipoServicoCategFiltro.SelectedValue;
            }
        }

        protected void CarregarServicoNome(object sender, EventArgs e, S_Servicos serv)
        {
            try
            {

                S_Servicos ss = serv;


                PanelbtnsServico.Visible = true;
                txtServicos.Text = "";
                lblMsgCadServicos.Text = "";
                btnNovoServico.Text = "Novo";
                //TabTarifas.Enabled = true;

                Session["nomeServico"] = ss.Servicos_Nome;
                Session["IdServico"] = ss.Servicos_Id;

                lblNomeServicoSS.Text = ss.Servicos_Nome;
                lblNomeServicoSUBS.Text = ss.Servicos_Nome;

                lblServicoNomeTituloTXT.Text = ss.Servicos_Nome;
                txtCodServico.Text = ss.Servicos_Id.ToString();
                txtNomeServico.Text = ss.Servicos_Nome;
                EditorInfoLongServicos.Content = ss.Servicos_descr;
                EditorInfoShortServicos.Content = ss.Servicos_descrCurt;
                txtremarks.Text = ss.Servicos_descrRemarks;
                txtInfoVoucher.Text = ss.Servicos_descrVoucher;
                txtInfoCliente.Text = ss.Servicos_descrCliente;
                ddlStatusServicos.SelectedValue = ss.STATUS_id.ToString();

                ddlTipoServico.SelectedValue = ss.Tipo_Id.ToString();
                ddlTipoServico2.SelectedValue = ss.Tipo_Id.ToString();

                if (Convert.ToBoolean(ss.Recommended)) chkRecommended.Checked = true; else chkRecommended.Checked = false;                

                popularDropTipoServicoCateg();
                PopularddlTipoCateg();
                ddlPaisServicos.SelectedValue = ss.Pais_Id.ToString();
                PopularddlCidade();
                ddlCidadeServicos.SelectedValue = ss.Cid_Id.ToString();
                lblNomeCidadeSS.Text = ddlCidadeServicos.SelectedItem.ToString();
                lblNomeCidadeSUBS.Text = ddlCidadeServicos.SelectedItem.ToString();

                if (ss.SIB == true) chkSIB.Checked = true; else chkSIB.Checked = false;

                //if (ss.Servicos_transfer != null)
                //{ ddlConfirmaTransfer.SelectedValue = ss.Servicos_transfer; }
                //else
                //{ ddlConfirmaTransfer.SelectedValue = "0"; }

                if (ss.Tipo_categ_id != null)
                { ddlTipoServicoCateg.SelectedValue = ss.Tipo_categ_id.ToString(); }
                else
                { ddlTipoServicoCateg.SelectedValue = "0"; }

                if (ss.Tipo_categ_id != null)
                { ddlTipoServicoCateg2.SelectedValue = ss.Tipo_categ_id.ToString(); }
                else
                { ddlTipoServicoCateg2.SelectedValue = "0"; }

                //Limpa tela serviço sozinho
                lblMsgCadMServicos.Text = "";
                btnSalvarTarifas.Text = "Salvar";
                PanelGridMServicoSozinho.Visible = false;
                popularDropTipoServico();
                popularDropTipoServicoCateg();
                from.Text = "";
                to.Text = "";
                txtSupplierMontaServico.Text = "";
                txtObs.Text = "";
                txtPorcentagemTaxa.Text = "0";
                txtPorcentagemImposto1.Text = "0";
                txtComissao.Text = "0";
                txtValorAdicional.Text = "0";
                txtPercentValorAdicional.Text = "0";
                chkPercentValorSS.Checked = false;
                btnAtualizarTarifas.Visible = false;
                txtSupplierMontaServico.Focus();
                //*

                txtSupplier.Text = "";
                PanelSubServicos.Visible = false;
                btnTemporadasCadastradas.Visible = false;
                PopulaGridSubServAdicionados(0);
                PopulaGridBase(0);

                PopulaHolidays();
            }
            catch (Exception ex)
            {
                System.Diagnostics.StackTrace trace = new System.Diagnostics.StackTrace(ex, true);
                Log.Save((trace.GetFrame(0).GetMethod().ReflectedType.FullName), ("Linha: " + trace.GetFrame(0).GetFileLineNumber()), ("Column: " + trace.GetFrame(0).GetFileColumnNumber()), ex.Message);

                lblMsgCadServicos.Text = ex.Message;
            }
        }

        protected void CarregarServicoNome_click(object sender, EventArgs e)
        {

            try
            {
                ServicoDAL s = new ServicoDAL();
                CidadeDAL cid = new CidadeDAL();

                string[] pars = txtServicos.Text.Split('°');

                string nomeS = pars[0].Remove(pars[0].Length - 1);
                string nomeCid = pars[1].Substring(1);

                int IdCidade = cid.ObterPorNome(nomeCid).CID_id;

                S_Servicos ss = s.ObterPorNome(nomeS, IdCidade);

                btnAtualizarServico.Visible = true;

                CarregarServicoNome(sender, e, ss);

                txtServicos.Focus();
            }
            catch (Exception ex)
            {
                System.Diagnostics.StackTrace trace = new System.Diagnostics.StackTrace(ex, true);
                Log.Save((trace.GetFrame(0).GetMethod().ReflectedType.FullName), ("Linha: " + trace.GetFrame(0).GetFileLineNumber()), ("Column: " + trace.GetFrame(0).GetFileColumnNumber()), ex.Message);

                lblMsgCadServicos.Text = ex.Message;
            }
        }

        protected void LimparServico(object sender, EventArgs e)
        {
            {
                //LimpaCampos(Controls);
                Session.Abandon();
                Response.Redirect("ServicosConsulta.aspx");
            }

        }

        protected void LimpaCampos(ControlCollection controls)
        {
            foreach (Control ctrl in controls)
            {
                if (ctrl is TextBox)
                {
                    (ctrl as TextBox).Text = string.Empty;
                }
                // ... demais controles que queira limpar

                LimpaCampos(ctrl.Controls);
            }
        }

        protected void btnFiltroNomeSupplier_Click(object sender, EventArgs e)
        {
            PopulaGridSubServAdicionados(0);
            PopulaGridBase(0);
            PanelSubServicos.Visible = true;
            //btnAddTemporada.Visible = true;
            //PopulaGridSubServAdicionados();
            btnTemporadasCadastradas.Visible = true;
            ViewState["NovaTemporadaSubServico"] = 0;
            //btnNovaTemporadaSubServico_Click(sender, e);
            ViewState["NovaTemporadaSubServico"] = 0;
            txtDataFromSubServico.Text = "";
            txtDataToSubServico.Text = "";
            //popularDropTipoServico3();
            PopulaGridBase(0);
            PopulaGridSubServAdicionados(0);
            btnCalculaServico.Visible = false;
            btnOpenAddSubServicos.Visible = false;
            imgRefresh.Visible = false;
        }

        protected string Limit(object Desc, int length)
        {
            StringBuilder strDesc = new StringBuilder();
            strDesc.Insert(0, Desc.ToString());

            if (strDesc.Length > length)
            {
                return strDesc.ToString().Substring(0, length);
            }
            else
            { return strDesc.ToString(); }
        }

        protected void imgRefresh_Click(object sender, ImageClickEventArgs e)
        {
            PopulaGridSubServAdicionados(Convert.ToInt32(ViewState["IdMontaSubServico"]));
            //PopulaGridBase();
        }

        protected void GridSubServAdicionados_Row(object sender, GridViewRowEventArgs e)
        {
            try
            {

                foreach (GridViewRow item in GridSubServAdicionados.Rows)
                {
                    Label lblDe = (Label)item.FindControl("lblDe");
                    string valor = item.Cells[4].Text;
                    ViewState["SubDe"] = lblDe.Text;
                    ViewState["valor"] = valor;
                }

            }
            catch (Exception ex)
            {
                System.Diagnostics.StackTrace trace = new System.Diagnostics.StackTrace(ex, true);
                Log.Save((trace.GetFrame(0).GetMethod().ReflectedType.FullName), ("Linha: " + trace.GetFrame(0).GetFileLineNumber()), ("Column: " + trace.GetFrame(0).GetFileColumnNumber()), ex.Message);

                lblMsgCadServicos.Text = ex.Message;
            }
        }

        protected void GridBases_Row(object sender, GridViewRowEventArgs e)
        {
            try
            {
                foreach (GridViewRow item in GridBases.Rows)
                {
                    Label lblPrecoTotal = (Label)item.FindControl("lblPrecoTotal");

                    string SubDe = ViewState["SubDe"].ToString();

                    double valor = Convert.ToDouble(ViewState["valor"]);

                    //double total = Convert.ToDouble(lblPrecoTotal.Text);

                    double d;

                    if (item.Cells[0].Text.Equals(SubDe))
                    {
                        if (!lblPrecoTotal.Text.Equals(""))
                        {
                            d = Convert.ToDouble(valor + Convert.ToDouble(lblPrecoTotal.Text));
                        }
                        else
                        {
                            d = Convert.ToDouble(valor);
                        }

                        lblPrecoTotal.Text = d.ToString("N2");
                    }

                }
            }
            catch (Exception ex)
            {
                System.Diagnostics.StackTrace trace = new System.Diagnostics.StackTrace(ex, true);
                Log.Save((trace.GetFrame(0).GetMethod().ReflectedType.FullName), ("Linha: " + trace.GetFrame(0).GetFileLineNumber()), ("Column: " + trace.GetFrame(0).GetFileColumnNumber()), ex.Message);

                lblMsgCadServicos.Text = ex.Message;
            }
        }

        protected void btnCalculaServico_Click(object sender, EventArgs e)
        {
            CalculaServico();
        }

        protected void CalculaServico()
        {
            try
            {
                string popUpConver = "";
                int qtdBases = GridBases.Rows.Count;
                int indexBase;
                List<S_Bases> listaBases = new List<S_Bases>();

                SBaseValorDAL sbd = new SBaseValorDAL();
                SBasesDAL sbdd = new SBasesDAL();
                SBaseValorDAL sbasedal = new SBaseValorDAL();
                MoedaDAL moedaDal = new MoedaDAL();

                foreach (GridViewRow it in GridBases.Rows)
                {
                    S_Bases_Valor sss = sbasedal.ObterPorIds(Convert.ToInt32(ViewState["IdMontaSubServico"]), Convert.ToInt32(it.Cells[3].Text));

                    if (sss != null)
                    {
                        sbasedal.Excluir(sss);
                    }
                }

                double total = 0;

                //PopulaGridSubServAdicionados(Convert.ToInt32(ViewState["IdMontaSubServico"]));

                foreach (GridViewRow item in GridSubServAdicionados.Rows)
                {

                    TextBox txtDe = (TextBox)item.FindControl("txtDe");
                    TextBox txtPara = (TextBox)item.FindControl("txtPara");
                    Label lblIdSupplier = (Label)item.FindControl("lblIdSupplier");
                    Label lblIdMServico = (Label)item.FindControl("lblIdMServico");

                    ServicoCompletoDAL scd = new ServicoCompletoDAL();


                    int IdServicoCompleto = Convert.ToInt32(item.Cells[4].Text);

                    Servico_Completo scIndex = scd.ObterPorId(IdServicoCompleto);

                    indexBase = Convert.ToInt32(scIndex.Base_Index);

                    if (scIndex != null)
                    {
                        Servico_Completo sc = new Servico_Completo();

                        sc.ServicoCompleto_id = IdServicoCompleto;
                        sc.ServicoCompleto_de = Convert.ToInt32(txtDe.Text);
                        sc.ServicoCompleto_ate = Convert.ToInt32(txtPara.Text);


                        scd.Atualizar(sc);
                    }
                    else
                    {
                        if (scd.ListarTodosTemporada(Convert.ToInt32(ViewState["IdMontaSubServico"])) == null)
                        {
                            PopulaGridBase(0);
                            return;
                        }

                    }

                    foreach (GridViewRow item2 in GridBases.Rows)
                    {

                        int DeBase = Convert.ToInt32(item2.Cells[0].Text);
                        int ParaBase = Convert.ToInt32(item2.Cells[1].Text);

                        if ((Convert.ToInt32(txtDe.Text) <= DeBase) && (Convert.ToInt32(txtPara.Text) >= ParaBase) ||
                            (Convert.ToInt32(txtPara.Text) >= DeBase) && (Convert.ToInt32(txtDe.Text) <= ParaBase))
                        {

                            MontaServicoValoresDAL msv = new MontaServicoValoresDAL();
                            S_Bases_Valor sb = new S_Bases_Valor();

                            int IdSupplier = Convert.ToInt32(lblIdSupplier.Text);
                            int IdMServico = Convert.ToInt32(lblIdMServico.Text);
                            listaBases = sbdd.ObterPorIdSupplierDeAte(IdSupplier, Convert.ToInt32(txtDe.Text), Convert.ToInt32(txtPara.Text), indexBase);
                            Boolean FlagMesmoSub = false;

                            foreach (S_Bases bases in listaBases)
                            {
                                qtdBases = qtdBases - 1;


                                if ((bases.Base_de <= DeBase) && (bases.Base_ate >= ParaBase) ||
                                    (bases.Base_de <= ParaBase) && (bases.Base_ate >= DeBase))
                                {

                                    CambioDAL cambDal = new CambioDAL();

                                    Monta_Servico_Valores mmsv = msv.ObterPorIdBase(bases.Base_id, IdMServico);

                                    double valorSub;

                                    int IntTeste = Convert.ToInt32(ViewState["IdMoedaBaseSubServico"]);

                                    if (mmsv.S_Bases.Moeda_id != IntTeste)
                                    {
                                        Cambio camb = cambDal.ObterPorIdMoedaPara(mmsv.S_Bases.Moeda_id, Convert.ToInt32(ViewState["IdMoedaBaseSubServico"]));
                                        double valorSubN = Convert.ToDouble(msv.ObterPorIdBase(bases.Base_id, IdMServico).MServico_Valores_Bulk_Total);

                                        valorSub = valorSubN * Convert.ToDouble(camb.Cambio1);

                                        Moeda moedaDe = moedaDal.ObterPorId(mmsv.S_Bases.Moeda_id);
                                        Moeda moedaPara = moedaDal.ObterPorId(Convert.ToInt32(ViewState["IdMoedaBaseSubServico"]));

                                        popUpConver = "de " + moedaDe.Moeda_sigla + " para " + moedaPara.Moeda_sigla;

                                        if (mmsv.S_Bases.TipoBase_id == 1)
                                        {
                                            double valorDiv = Convert.ToDouble(DeBase);
                                            valorSub = valorSub / valorDiv;
                                        }
                                    }
                                    else
                                    {
                                        if (mmsv.S_Bases.TipoBase_id == 1)
                                        {
                                            valorSub = Convert.ToDouble(msv.ObterPorIdBase(bases.Base_id, IdMServico).MServico_Valores_Bulk_Total);

                                            double valorDiv = Convert.ToDouble(DeBase);

                                            valorSub = valorSub / valorDiv;

                                        }
                                        else
                                        {
                                            valorSub = Convert.ToDouble(msv.ObterPorIdBase(bases.Base_id, IdMServico).MServico_Valores_Bulk_Total);
                                        }
                                    }

                                    if (FlagMesmoSub)
                                    {
                                        valorSub = 0;
                                    }

                                    S_Bases_Valor s = sbd.ObterPorIds(Convert.ToInt32(ViewState["IdMontaSubServico"]), Convert.ToInt32(item2.Cells[3].Text));

                                    if (s != null)
                                    {
                                        total = (Convert.ToDouble(s.S_Bases_Valor_valor) + valorSub);

                                        sb.S_Bases_Valor_id = s.S_Bases_Valor_id;
                                        sb.S_Bases_Valor_valor = Convert.ToDecimal(total);
                                        sb.Base_id = Convert.ToInt32(item2.Cells[3].Text);
                                        sb.IdMServico = Convert.ToInt32(ViewState["IdMontaSubServico"]);

                                        sbd.Atualizar(sb);
                                    }
                                    else
                                    {
                                        sb.S_Bases_Valor_valor = Convert.ToDecimal(valorSub);
                                        sb.Base_id = Convert.ToInt32(item2.Cells[3].Text);
                                        sb.IdMServico = Convert.ToInt32(ViewState["IdMontaSubServico"]);

                                        sbd.Salvar(sb);
                                    }
                                    FlagMesmoSub = true;
                                }
                            }
                        }
                    }

                    List<S_Bases_Valor> listaBaseValor = sbd.ListarTodos(Convert.ToInt32(ViewState["IdMontaSubServico"]));
                    List<S_Bases> listaBaseTotalSupp = sbdd.ObterPorIdSupplierIndex(Convert.ToInt32(ViewState["IdSupplierSubServicoPrincipal"]), Convert.ToInt32(rdoBasesIndexSubServico.SelectedValue));

                    if (listaBaseValor.Count() < listaBaseTotalSupp.Count)
                    {
                        var t = listaBaseTotalSupp.Where(l => !listaBaseValor.Select(l1 => l1.Base_id).Contains(l.Base_id));

                        foreach (var tt in t)
                        {
                            S_Bases_Valor sb2 = new S_Bases_Valor();

                            sb2.Base_id = tt.Base_id;
                            sb2.S_Bases_Valor_valor = Convert.ToDecimal(0);
                            sb2.IdMServico = Convert.ToInt32(ViewState["IdMontaSubServico"]);

                            sbd.Salvar(sb2);
                        }
                    }
                }

                PopulaGridBase(Convert.ToInt32(ViewState["IdMontaSubServico"]));

                if (popUpConver != "")
                {
                    MostrarMsg("Houve conversão na(s) Categoria(s) " + popUpConver);
                }

                popUpConver = "";

                lblMsgCadSubServico.Text = "";
                MostrarMsg("Solicitação realizada com sucesso.");
            }
            catch (Exception ex)
            {
                System.Diagnostics.StackTrace trace = new System.Diagnostics.StackTrace(ex, true);
                Log.Save((trace.GetFrame(0).GetMethod().ReflectedType.FullName), ("Linha: " + trace.GetFrame(0).GetFileLineNumber()), ("Column: " + trace.GetFrame(0).GetFileColumnNumber()), ex.Message);

                lblMsgCadSubServico.Text = ex.Message;
            }
        }

        #endregion

        protected void MostrarMsg(string Msg)
        {
            ScriptManager.RegisterStartupScript(this.Page, Page.GetType(), "call me", "showAutoCloseMessage('" + Msg + "')", true);
        }

        public class ModeloServico
        {

            private string idServico;
            public string IdServico
            {
                get { return idServico; }
                set { idServico = value; }
            }

            private string idSupplier;
            public string IdSupplier
            {
                get { return idSupplier; }
                set { idSupplier = value; }
            }


        }

        public class ModeloCidade
        {

            private string idCidade;
            public string IdCidade
            {
                get { return idCidade; }
                set { idCidade = value; }
            }

            private string sigla;
            public string Sigla
            {
                get { return sigla; }
                set { sigla = value; }
            }


        }

        protected void btnGerarRelatorioServico_Click(object sender, EventArgs e)
        {

            DSServicos ds = new DSServicos();

            DataTable dt = ds.Tables["Servicos"];

            string[] pars = ConfigurationManager.ConnectionStrings["NewTierraEntities"].ToString().Split('\"');
            SqlConnection Con = new SqlConnection(pars[1]);
            string sql;
            string sql2;
            string sql3;
            string sql4;
            string sql5;
            string sql6;
            string sql7;
            string sql8;

            DateTime dataFrom = DateTime.ParseExact(txtfromReport.Text, "dd/MM/yyyy", CultureInfo.InvariantCulture);
            DateTime dataTo = DateTime.ParseExact(txttoReport.Text, "dd/MM/yyyy", CultureInfo.InvariantCulture);

            decimal cambio = 1;
            decimal total;
            string totalString;
            Utils utils = new Utils();

            Con.Open();

            sql = "SELECT DISTINCT(S_Servicos.Cid_Id), Cidade.CID_nome ";
            sql = sql + "FROM Monta_Servico_Valores  ";
            sql = sql + "INNER JOIN Monta_Servico ON Monta_Servico_Valores.IdMServico = Monta_Servico.IdMServico ";
            sql = sql + "INNER JOIN S_Bases ON Monta_Servico_Valores.Base_id = S_Bases.Base_id ";
            sql = sql + "INNER JOIN Servico_Completo ON Monta_Servico.IdMServico = Servico_Completo.IdMServico ";
            sql = sql + "INNER JOIN S_Servicos ON Servico_Completo.Servicos_Id = S_Servicos.Servicos_Id ";
            sql = sql + "INNER JOIN Cidade ON S_Servicos.Cid_Id = Cidade.CID_id ";
            sql = sql + "LEFT OUTER JOIN S_Mercado_Tarifa_Status ON S_Mercado_Tarifa_Status.S_mercado_tarifa_status_id = Monta_Servico_Valores.S_mercado_tarifa_status_id ";
            sql = sql + "WHERE S_Servicos.PAIS_id = " + Convert.ToInt32(ddlPaisReport.SelectedValue);
            if (Convert.ToInt32(ddlCidadeReport.SelectedValue) != 0)
            {
                sql = sql + " AND S_Servicos.Cid_Id = " + Convert.ToInt32(ddlCidadeReport.SelectedValue);
            }
            sql = sql + " ORDER BY 2 ";

            SqlCommand cmd = new SqlCommand(sql, Con);
            SqlDataReader reader = cmd.ExecuteReader();

            DataRow drw = dt.NewRow();

            List<string> listaCidades = new List<string>();
            string cidade;

            List<ModeloServico> listaServicos;
            ModeloServico servicos;


            List<string> listaBases;

            string d;
            string idSupplier = "";

            while (reader.Read())
            {
                cidade = reader["Cid_Id"].ToString();
                listaCidades.Add(cidade);

            }


            foreach (string item in listaCidades)
            {

                sql2 = "SELECT DISTINCT(S_Servicos.Servicos_Id), S_Servicos.Servicos_Nome, Cidade.CID_nome ";
                sql2 = sql2 + "FROM Monta_Servico_Valores  ";
                sql2 = sql2 + "INNER JOIN Monta_Servico ON Monta_Servico_Valores.IdMServico = Monta_Servico.IdMServico ";
                sql2 = sql2 + "INNER JOIN S_Bases ON Monta_Servico_Valores.Base_id = S_Bases.Base_id ";
                sql2 = sql2 + "INNER JOIN Servico_Completo ON Monta_Servico.IdMServico = Servico_Completo.IdMServico ";
                sql2 = sql2 + "INNER JOIN S_Servicos ON Servico_Completo.Servicos_Id = S_Servicos.Servicos_Id ";
                sql2 = sql2 + "INNER JOIN Cidade ON S_Servicos.Cid_Id = Cidade.CID_id ";
                sql2 = sql2 + "LEFT OUTER JOIN S_Mercado_Tarifa_Status ON S_Mercado_Tarifa_Status.S_mercado_tarifa_status_id = Monta_Servico_Valores.S_mercado_tarifa_status_id ";
                sql2 = sql2 + "WHERE S_Servicos.Cid_Id = " + item;

                if (Convert.ToInt32(ddlBaseTarifariaReport.SelectedValue) != 0)
                {
                    sql2 = sql2 + "AND BaseTarifaria_id = " + Convert.ToInt32(ddlBaseTarifariaReport.SelectedValue);
                }
                if (Convert.ToInt32(ddlMercadoReport.SelectedValue) != 0)
                {
                    sql2 = sql2 + "AND Mercado_id = " + Convert.ToInt32(ddlMercadoReport.SelectedValue);
                }

                sql2 = sql2 + " AND MServico_DataFrom >= '" + dataFrom.ToString("yyyyMMdd") + "' and MServico_DataTo <= '" + dataTo.ToString("yyyyMMdd") + "'";

                SqlCommand cmd2 = new SqlCommand(sql2, Con);
                SqlDataReader reader2 = cmd2.ExecuteReader();

                listaServicos = new List<ModeloServico>();
                cidade = "";

                bool preenche = false;
                while (reader2.Read())
                {
                    cidade = reader2["CID_nome"].ToString();

                    servicos = new ModeloServico();
                    servicos.IdServico = reader2["Servicos_Id"].ToString();
                    servicos.IdSupplier = "";//reader2["S_id"].ToString();
                    listaServicos.Add(servicos);

                    preenche = true;
                }

                if (preenche)
                {
                    drw = dt.NewRow();
                    drw["CServico"] = cidade;
                    dt.Rows.Add(drw);
                }



                foreach (ModeloServico item2 in listaServicos)
                {



                    sql6 = "SELECT DISTINCT(Servico_Completo.SubServico) ";
                    sql6 = sql6 + "FROM Monta_Servico_Valores  ";
                    sql6 = sql6 + "INNER JOIN Monta_Servico ON Monta_Servico_Valores.IdMServico = Monta_Servico.IdMServico ";
                    sql6 = sql6 + "INNER JOIN S_Bases ON Monta_Servico_Valores.Base_id = S_Bases.Base_id ";
                    sql6 = sql6 + "INNER JOIN Servico_Completo ON Monta_Servico.IdMServico = Servico_Completo.IdMServico ";
                    sql6 = sql6 + "INNER JOIN S_Servicos ON Servico_Completo.Servicos_Id = S_Servicos.Servicos_Id ";
                    sql6 = sql6 + "WHERE S_Servicos.Servicos_Id = " + item2.IdServico;

                    SqlCommand cmd6 = new SqlCommand(sql6, Con);
                    SqlDataReader reader6 = cmd6.ExecuteReader();

                    bool subServico = false;
                    string txtSubServico = "";

                    while (reader6.Read())
                    {

                        txtSubServico = reader6["SubServico"].ToString();
                        if (!txtSubServico.Equals(""))
                        {
                            subServico = true;
                        }
                    }

                    if (!subServico)
                    {




                        sql3 = "SELECT DISTINCT(CAST(Base_de AS VARCHAR(5)) + '/' + CAST(Base_ate AS VARCHAR(5))) as Base, Base_ate, S_Servicos.Servicos_Nome ";
                        sql3 = sql3 + "FROM S_Bases_Valor ";
                        sql3 = sql3 + "INNER JOIN Monta_Servico ON S_Bases_Valor.IdMServico = Monta_Servico.IdMServico ";
                        sql3 = sql3 + "INNER JOIN S_Bases ON S_Bases_Valor.Base_id = S_Bases.Base_id ";
                        sql3 = sql3 + "INNER JOIN Servico_Completo ON Monta_Servico.IdMServico = Servico_Completo.IdMServico_Temporada ";
                        sql3 = sql3 + "INNER JOIN S_Servicos ON Servico_Completo.Servicos_Id = S_Servicos.Servicos_Id ";
                        sql3 = sql3 + "INNER JOIN Cidade ON S_Servicos.Cid_Id = Cidade.CID_id ";
                        sql3 = sql3 + "WHERE S_Servicos.Servicos_Id = " + item2.IdServico;
                        sql3 = sql3 + " ORDER BY Base_ate ";
                    }
                    else
                    {


                        sql8 = "SELECT TOP(1) Monta_Servico.S_id ";
                        sql8 = sql8 + "FROM Monta_Servico_Valores  ";
                        sql8 = sql8 + "INNER JOIN Monta_Servico ON Monta_Servico_Valores.IdMServico = Monta_Servico.IdMServico ";
                        sql8 = sql8 + "INNER JOIN S_Bases ON Monta_Servico_Valores.Base_id = S_Bases.Base_id ";
                        sql8 = sql8 + "INNER JOIN Servico_Completo ON Monta_Servico.IdMServico = Servico_Completo.IdMServico ";
                        sql8 = sql8 + "INNER JOIN S_Servicos ON Servico_Completo.Servicos_Id = S_Servicos.Servicos_Id ";
                        sql8 = sql8 + "INNER JOIN Cidade ON S_Servicos.Cid_Id = Cidade.CID_id ";
                        sql8 = sql8 + "LEFT OUTER JOIN S_Mercado_Tarifa_Status ON S_Mercado_Tarifa_Status.S_mercado_tarifa_status_id = Monta_Servico_Valores.S_mercado_tarifa_status_id ";
                        sql8 = sql8 + "WHERE S_Servicos.Cid_Id = " + item;
                        sql8 = sql8 + " AND S_Servicos.Servicos_Id = " + item2.IdServico; ;
                        sql8 = sql8 + " ORDER BY S_id ";

                        SqlCommand cmd8 = new SqlCommand(sql8, Con);
                        SqlDataReader reader8 = cmd8.ExecuteReader();

                        while (reader8.Read())
                        {
                            item2.IdSupplier = reader8["S_id"].ToString();
                        }


                        sql3 = "SELECT DISTINCT(CAST(Base_de AS VARCHAR(5)) + '/' + CAST(Base_ate AS VARCHAR(5))) as Base, Base_ate, S_Servicos.Servicos_Nome ";
                        sql3 = sql3 + "FROM Monta_Servico_Valores  ";
                        sql3 = sql3 + "INNER JOIN Monta_Servico ON Monta_Servico_Valores.IdMServico = Monta_Servico.IdMServico ";
                        sql3 = sql3 + "INNER JOIN S_Bases ON Monta_Servico_Valores.Base_id = S_Bases.Base_id ";
                        sql3 = sql3 + "INNER JOIN Servico_Completo ON Monta_Servico.IdMServico = Servico_Completo.IdMServico ";
                        sql3 = sql3 + "INNER JOIN S_Servicos ON Servico_Completo.Servicos_Id = S_Servicos.Servicos_Id ";
                        sql3 = sql3 + "INNER JOIN Cidade ON S_Servicos.Cid_Id = Cidade.CID_id ";
                        sql3 = sql3 + "LEFT OUTER JOIN S_Mercado_Tarifa_Status ON S_Mercado_Tarifa_Status.S_mercado_tarifa_status_id = Monta_Servico_Valores.S_mercado_tarifa_status_id ";
                        sql3 = sql3 + "WHERE S_Servicos.Servicos_Id = " + item2.IdServico;
                        sql3 = sql3 + "AND Monta_Servico.S_id = " + item2.IdSupplier;
                        sql3 = sql3 + " ORDER BY Base_ate ";
                    }


                    SqlCommand cmd3 = new SqlCommand(sql3, Con);
                    SqlDataReader reader3 = cmd3.ExecuteReader();

                    listaBases = new List<string>();
                    string servico = "";
                    idSupplier = item2.IdSupplier;

                    drw = dt.NewRow();

                    while (reader3.Read())
                    {
                        servico = reader3["Servicos_Nome"].ToString();
                        listaBases.Add(reader3["Base"].ToString());
                    }

                    drw["Servico"] = servico;
                    dt.Rows.Add(drw);

                    drw = dt.NewRow();

                    for (int i = 0; i < listaBases.Count; i++)
                    {
                        d = "C" + Convert.ToString(i + 1);
                        drw[d] = listaBases[i];
                    }

                    dt.Rows.Add(drw);

                    drw = dt.NewRow();



                    sql5 = "SELECT ";
                    if (!subServico)
                    {
                        sql5 = sql5 + "TOP(1) Monta_Servico.IdMServico AS IdServico, Monta_Servico.MServico_DataFrom ";
                    }
                    else
                    {
                        sql5 = sql5 + "DISTINCT(Monta_Servico.IdMServico) AS IdServico, Monta_Servico.MServico_DataFrom ";
                    }
                    sql5 = sql5 + "FROM Monta_Servico_Valores  ";
                    sql5 = sql5 + "INNER JOIN Monta_Servico ON Monta_Servico_Valores.IdMServico = Monta_Servico.IdMServico ";
                    sql5 = sql5 + "INNER JOIN S_Bases ON Monta_Servico_Valores.Base_id = S_Bases.Base_id ";
                    sql5 = sql5 + "INNER JOIN Servico_Completo ON Monta_Servico.IdMServico = Servico_Completo.IdMServico ";
                    sql5 = sql5 + "INNER JOIN S_Servicos ON Servico_Completo.Servicos_Id = S_Servicos.Servicos_Id ";
                    sql5 = sql5 + "INNER JOIN Cidade ON S_Servicos.Cid_Id = Cidade.CID_id ";
                    sql5 = sql5 + "LEFT OUTER JOIN S_Mercado_Tarifa_Status ON S_Mercado_Tarifa_Status.S_mercado_tarifa_status_id = Monta_Servico_Valores.S_mercado_tarifa_status_id ";
                    sql5 = sql5 + "WHERE S_Servicos.Servicos_Id = " + item2.IdServico;
                    if (subServico)
                    {
                        sql5 = sql5 + "AND Monta_Servico.S_id = " + idSupplier;
                    }
                    sql5 = sql5 + " ORDER BY Monta_Servico.MServico_DataFrom, IdServico ";

                    SqlCommand cmd5 = new SqlCommand(sql5, Con);
                    SqlDataReader reader5 = cmd5.ExecuteReader();

                    while (reader5.Read())
                    {

                        if (!subServico)
                        {

                            sql7 = "SELECT Cidade.CID_nome, Monta_Servico.MServico_DataFrom, Monta_Servico.MServico_DataTo, S_Servicos.Servicos_Nome, S_Bases.Base_de, S_Bases.Base_ate, S_Bases.Moeda_id, S_Bases_Valor.S_Bases_Valor_valor, '' as S_mercado_tarifa_status_nome, Moeda_id  ";
                            sql7 = sql7 + "FROM S_Bases_Valor ";
                            sql7 = sql7 + "INNER JOIN Monta_Servico ON S_Bases_Valor.IdMServico = Monta_Servico.IdMServico ";
                            sql7 = sql7 + "INNER JOIN S_Bases ON S_Bases_Valor.Base_id = S_Bases.Base_id ";
                            sql7 = sql7 + "INNER JOIN Servico_Completo ON Monta_Servico.IdMServico = Servico_Completo.IdMServico_Temporada ";
                            sql7 = sql7 + "INNER JOIN S_Servicos ON Servico_Completo.Servicos_Id = S_Servicos.Servicos_Id ";
                            sql7 = sql7 + "INNER JOIN Cidade ON S_Servicos.Cid_Id = Cidade.CID_id ";
                            sql7 = sql7 + "WHERE S_Servicos.Servicos_Id = " + item2.IdServico;
                            sql7 = sql7 + "AND Servico_Completo.IdMServico = " + reader5["IdServico"];
                            sql7 = sql7 + " ORDER BY Cidade.CID_nome, S_Servicos.Servicos_Nome, Monta_Servico.MServico_DataFrom, S_Bases.Base_ate, S_Bases.Base_de ";

                            SqlCommand cmd7 = new SqlCommand(sql7, Con);
                            SqlDataReader reader7 = cmd7.ExecuteReader();

                            //bool passou = false;
                            int coluna = 1;
                            while (reader7.Read())
                            {

                                if (Convert.ToInt32(reader7["Moeda_id"]) != Convert.ToInt32(ddlCambioReport.SelectedValue) && !ddlCambioReport.SelectedValue.Equals("0"))
                                {
                                    cambio = utils.CalcularCambio(Convert.ToInt32(reader7["Moeda_id"]), Convert.ToInt32(ddlCambioReport.SelectedValue));
                                }



                                //drw["Servico"] = "";

                                //if (passou == false)
                                //{
                                //drw["Servico"] = reader7["MServico_DataFrom"];

                                drw["D20"] = string.Format(new System.Globalization.CultureInfo("en-GB"), "{0:MMM, dd yyyy}", reader7["MServico_DataFrom"]) + " - " + string.Format(new System.Globalization.CultureInfo("en-GB"), "{0:MMM, dd yyyy}", reader7["MServico_DataTo"]);
                                //drw["D20"] = String.Format("{0:dd/MM/yyyy}", reader7["MServico_DataFrom"]) + " - " + String.Format("{0:dd/MM/yyyy}", reader7["MServico_DataTo"]);
                                //drw["D6"] = String.Format("{0:d/M/yyyy}", reader7["MServico_DataFrom"]);
                                //drw["D7"] = " -     .";
                                //drw["D8"] = String.Format("{0:d/M/yyyy}", reader7["MServico_DataTo"]);
                                //dt.Rows.Add(drw);
                                //drw = dt.NewRow();
                                //passou = true;
                                //}



                                d = "D" + coluna.ToString();

                                if (coluna < 19)
                                {
                                    total = Convert.ToDecimal(NuloZero(reader7["S_Bases_Valor_valor"].ToString())) * cambio;
                                    totalString = Convert.ToString(total.ToString("N2"));
                                    drw[d] = totalString;
                                }

                                coluna = coluna + 1;

                            }

                        }
                        else
                        {
                            sql4 = "SELECT Cidade.CID_nome, Monta_Servico.MServico_DataFrom, Monta_Servico.MServico_DataTo, S_Servicos.Servicos_Nome, S_Bases.Base_de, S_Bases.Base_ate, S_Bases.Moeda_id, ";
                            sql4 = sql4 + "Monta_Servico_Valores.MServico_Valores_Bulk_Total, S_mercado_tarifa_status_nome, Servico_Completo.SubServico, Servico_Completo.IdMServico_Temporada ";
                            sql4 = sql4 + "FROM Monta_Servico_Valores  ";
                            sql4 = sql4 + "INNER JOIN Monta_Servico ON Monta_Servico_Valores.IdMServico = Monta_Servico.IdMServico ";
                            sql4 = sql4 + "INNER JOIN S_Bases ON Monta_Servico_Valores.Base_id = S_Bases.Base_id ";
                            sql4 = sql4 + "INNER JOIN Servico_Completo ON Monta_Servico.IdMServico = Servico_Completo.IdMServico ";
                            sql4 = sql4 + "INNER JOIN S_Servicos ON Servico_Completo.Servicos_Id = S_Servicos.Servicos_Id ";
                            sql4 = sql4 + "INNER JOIN Cidade ON S_Servicos.Cid_Id = Cidade.CID_id ";
                            sql4 = sql4 + "LEFT OUTER JOIN S_Mercado_Tarifa_Status ON S_Mercado_Tarifa_Status.S_mercado_tarifa_status_id = Monta_Servico_Valores.S_mercado_tarifa_status_id ";
                            sql4 = sql4 + "WHERE S_Servicos.Servicos_Id = " + item2.IdServico;
                            sql4 = sql4 + "AND Monta_Servico.IdMServico = " + reader5["IdServico"];
                            sql4 = sql4 + " ORDER BY Cidade.CID_nome, S_Servicos.Servicos_Nome, Monta_Servico.MServico_DataFrom, S_Bases.Base_ate, S_Bases.Base_de ";

                            SqlCommand cmd4 = new SqlCommand(sql4, Con);
                            SqlDataReader reader4 = cmd4.ExecuteReader();

                            //bool passou = false;
                            int coluna = 1;
                            while (reader4.Read())
                            {


                                if (reader4["MServico_Valores_Bulk_Total"].ToString().Equals(""))
                                {
                                    totalString = reader4["S_mercado_tarifa_status_nome"].ToString();
                                }
                                else
                                {
                                    if (Convert.ToInt32(reader4["Moeda_id"]) != Convert.ToInt32(ddlCambioReport.SelectedValue) && !ddlCambioReport.SelectedValue.Equals("0"))
                                    {
                                        cambio = utils.CalcularCambio(Convert.ToInt32(reader4["Moeda_id"]), Convert.ToInt32(ddlCambioReport.SelectedValue));
                                    }


                                    total = Convert.ToDecimal(reader4["MServico_Valores_Bulk_Total"].ToString()) * cambio;
                                    totalString = Convert.ToString(total.ToString("N2"));
                                }

                                //drw["Servico"] = ""; 
                                //if (passou == false)
                                //{
                                //drw["Servico"] = reader4["MServico_DataFrom"];

                                drw["D20"] = string.Format(new System.Globalization.CultureInfo("en-GB"), "{0:MMM, dd yyyy}", reader4["MServico_DataFrom"]) + " - " + string.Format(new System.Globalization.CultureInfo("en-GB"), "{0:MMM, dd yyyy}", reader4["MServico_DataTo"]);
                                //drw["D20"] = String.Format("{0:dd/MM/yyyy}", reader4["MServico_DataFrom"]) + " - " + String.Format("{0:dd/MM/yyyy}", reader4["MServico_DataTo"]);
                                //drw["D7"] = " -     .";
                                //drw["D8"] = String.Format("{0:d/M/yyyy}", reader4["MServico_DataTo"]);

                                //    dt.Rows.Add(drw);
                                //    drw = dt.NewRow();
                                //    passou = true;
                                //}

                                d = "D" + coluna.ToString();
                                drw[d] = totalString;

                                coluna = coluna + 1;

                            }
                        }

                        dt.Rows.Add(drw);

                        drw = dt.NewRow();
                    }

                }

            }

            RptServicos rpt = new RptServicos();

            rpt.SetDataSource(dt);


            rpt.ExportToHttpResponse(ExportFormatType.PortableDocFormat, Response, true, "tarifarioservicos");

        }

        protected void btnGerarRelatorioServicoPopUp_Click(object sender, EventArgs e)
        {

            try
            {
                modalPopupExtenderRelatorioServico.Show();
            }
            catch (Exception ex)
            {

                MostrarMsg(ex.Message);
            }

        }

        protected void btnGerarRelatorioServicoPopUpTarifario_Click(object sender, EventArgs e)
        {

            try
            {
                modalPopupExtenderRelatorioServicoTarifario.Show();
            }
            catch (Exception ex)
            {

                MostrarMsg(ex.Message);
            }

        }

        protected Decimal arrendodar(Decimal valor)
        {
            decimal valorArr = 0;
            try
            {
                string[] pars = Convert.ToDecimal(valor).ToString().Split(',');
                double valorArredondado = 0;
                ArredondaDAL arrd = new ArredondaDAL();
                if (pars.Count() > 1)
                {
                    Arredonda arr;

                    if (pars[1].Length == 1)
                    {
                        string val = pars[1] + 0;
                        arr = arrd.ObterArr(Convert.ToInt32(val.Substring(0, 2)));
                    }
                    else
                    {
                        arr = arrd.ObterArr(Convert.ToInt32(pars[1].Substring(0, 2)));
                    }

                    if (arr.Arredonda_recebe < 1)
                    {
                        valorArr = Convert.ToDecimal(pars[0]) + Convert.ToDecimal(arr.Arredonda_recebe);
                        valorArredondado = Convert.ToDouble(valorArr);
                    }
                    else
                    {
                        valorArr = Convert.ToDecimal(pars[0]) + Convert.ToDecimal(arr.Arredonda_recebe);
                        valorArredondado = Convert.ToDouble(valorArr);
                    }
                }

                return valorArr;

            }
            catch (Exception ex)
            {
                MostrarMsg(ex.Message);
            }

            return valorArr;
        }

        protected void btnGerarRelatorioServicoTarifario_Click(object sender, EventArgs e)
        {

            try
            {



                DSServicos ds = new DSServicos();

                DataTable dt = ds.Tables["Servicos"];

                string[] pars = ConfigurationManager.ConnectionStrings["NewTierraEntities"].ToString().Split('\"');
                SqlConnection Con = new SqlConnection(pars[1]);
                string sql;
                string sql2;
                string sql3;
                string sql4;
                string sql5;
                string sql6;
                string sql7;
                string sql8;

                bool cabecalho = true;
                bool sib = true;
                bool naoSib = true;
                bool adiciona = false;

                DateTime dataFrom = DateTime.ParseExact(txtfromReportTarifario.Text, "dd/MM/yyyy", CultureInfo.InvariantCulture);
                DateTime dataTo = DateTime.ParseExact(txttoReportTarifario.Text, "dd/MM/yyyy", CultureInfo.InvariantCulture);

                decimal markUp = 0;
                if (!txtMarkUpRelatorioTarifario.Text.Equals(""))
                {
                    markUp = Convert.ToDecimal(txtMarkUpRelatorioTarifario.Text);
                }

                decimal cambio = 1;
                decimal total;
                string totalString;
                Utils utils = new Utils();

                Con.Open();

                sql = "SELECT DISTINCT(S_Servicos.Cid_Id), Cidade.CID_nome, Cidade.CID_uf ";
                sql = sql + "FROM Monta_Servico_Valores  ";
                sql = sql + "INNER JOIN Monta_Servico ON Monta_Servico_Valores.IdMServico = Monta_Servico.IdMServico ";
                sql = sql + "INNER JOIN S_Bases ON Monta_Servico_Valores.Base_id = S_Bases.Base_id ";
                sql = sql + "INNER JOIN Servico_Completo ON Monta_Servico.IdMServico = Servico_Completo.IdMServico ";
                sql = sql + "INNER JOIN S_Servicos ON Servico_Completo.Servicos_Id = S_Servicos.Servicos_Id ";
                sql = sql + "INNER JOIN Cidade ON S_Servicos.Cid_Id = Cidade.CID_id ";
                sql = sql + "LEFT OUTER JOIN S_Mercado_Tarifa_Status ON S_Mercado_Tarifa_Status.S_mercado_tarifa_status_id = Monta_Servico_Valores.S_mercado_tarifa_status_id ";
                sql = sql + "WHERE S_Servicos.PAIS_id = " + Convert.ToInt32(ddlPaisReportTarifario.SelectedValue);
                if (Convert.ToInt32(ddlCidadeRerpotTarifario.SelectedValue) != 0)
                {
                    sql = sql + " AND S_Servicos.Cid_Id = " + Convert.ToInt32(ddlCidadeRerpotTarifario.SelectedValue);
                }
                sql = sql + " ORDER BY 2 ";

                SqlCommand cmd = new SqlCommand(sql, Con);
                SqlDataReader reader = cmd.ExecuteReader();

                DataRow drw = dt.NewRow();

                List<ModeloCidade> listaCidades = new List<ModeloCidade>();
                ModeloCidade modeloCidade = new ModeloCidade();

                string cidade;

                List<ModeloServico> listaServicos;
                ModeloServico servicos;

                List<string> listaBases;

                string d;
                string idSupplier = "";

                while (reader.Read())
                {
                    modeloCidade = new ModeloCidade();
                    modeloCidade.IdCidade = reader["Cid_Id"].ToString();
                    modeloCidade.Sigla = reader["CID_uf"].ToString();

                    listaCidades.Add(modeloCidade);
                }


                foreach (ModeloCidade item in listaCidades)
                {

                    cabecalho = true;
                    sib = true;
                    naoSib = true;


                    sql2 = "SELECT DISTINCT S_Servicos.Servicos_Nome, S_Servicos.Servicos_Id, Supplier.S_nome, Cidade.CID_nome, 'SIB' = case when S_Servicos.SIB IS NULL then (0) ELSE S_Servicos.SIB end, S_Servicos_Tipo_Categ.Ordenacao ";
                    sql2 = sql2 + "FROM  Supplier ";
                    sql2 = sql2 + "INNER JOIN S_Bases ON Supplier.S_id = S_Bases.S_id ";
                    sql2 = sql2 + "INNER JOIN Monta_Servico ON Supplier.S_id = Monta_Servico.S_id ";
                    sql2 = sql2 + "INNER JOIN Servico_Completo ON Monta_Servico.IdMServico = Servico_Completo.IdMServico_Temporada ";
                    sql2 = sql2 + "INNER JOIN S_Servicos ON Servico_Completo.Servicos_Id = S_Servicos.Servicos_Id ";

                    sql2 = sql2 + "INNER JOIN S_Servicos_Tipo_Categ ON S_Servicos.Tipo_categ_id = S_Servicos_Tipo_Categ.Tipo_categ_id ";

                    sql2 = sql2 + "INNER JOIN Cidade ON S_Servicos.Cid_Id = Cidade.CID_id ";

                    sql2 = sql2 + "WHERE S_Servicos.Cid_Id = " + item.IdCidade;
                    sql2 = sql2 + " AND MServico_DataFrom <= '" + dataFrom.ToString("yyyyMMdd") + "' and MServico_DataTo >= '" + dataTo.ToString("yyyyMMdd") + "'";

                    if (Convert.ToInt32(ddlBaseTarifariaReportTarifario.SelectedValue) != 0)
                    {
                        sql2 = sql2 + "AND BaseTarifaria_id = " + Convert.ToInt32(ddlBaseTarifariaReportTarifario.SelectedValue);
                    }
                    if (Convert.ToInt32(ddlMercadoReportTarifario.SelectedValue) != 0)
                    {
                        sql2 = sql2 + "AND Mercado_id = " + Convert.ToInt32(ddlMercadoReportTarifario.SelectedValue);
                    }

                    if (!item.Sigla.Equals("RJ"))
                    {
                        sql2 = sql2 + " AND Supplier.Tarifario = 'True' ";
                    }

                    ////COMEÇA OR

                    sql2 = sql2 + " OR S_Servicos.Cid_Id = " + item.IdCidade;
                    sql2 = sql2 + " AND MServico_DataFrom <= '" + dataTo.ToString("yyyyMMdd") + "' and MServico_DataTo >= '" + dataFrom.ToString("yyyyMMdd") + "'";

                    if (Convert.ToInt32(ddlBaseTarifariaReportTarifario.SelectedValue) != 0)
                    {
                        sql2 = sql2 + "AND BaseTarifaria_id = " + Convert.ToInt32(ddlBaseTarifariaReportTarifario.SelectedValue);
                    }
                    if (Convert.ToInt32(ddlMercadoReportTarifario.SelectedValue) != 0)
                    {
                        sql2 = sql2 + "AND Mercado_id = " + Convert.ToInt32(ddlMercadoReportTarifario.SelectedValue);
                    }

                    if (!item.Sigla.Equals("RJ"))
                    {
                        sql2 = sql2 + " AND Supplier.Tarifario = 'True' ";
                    }

                    sql2 = sql2 + "UNION ALL ";

                    sql2 = sql2 + "SELECT DISTINCT S_Servicos.Servicos_Nome, S_Servicos.Servicos_Id, Supplier.S_nome, Cidade.CID_nome, 'SIB' = case when S_Servicos.SIB IS NULL then (0) ELSE S_Servicos.SIB end, S_Servicos_Tipo_Categ.Ordenacao ";
                    sql2 = sql2 + "FROM Monta_Servico_Valores ";
                    sql2 = sql2 + "INNER JOIN Monta_Servico ON Monta_Servico_Valores.IdMServico = Monta_Servico.IdMServico ";
                    sql2 = sql2 + "INNER JOIN S_Bases ON Monta_Servico_Valores.Base_id = S_Bases.Base_id ";
                    sql2 = sql2 + "INNER JOIN Supplier ON Supplier.S_id = S_Bases.S_id ";
                    sql2 = sql2 + "INNER JOIN Servico_Completo ON Monta_Servico.IdMServico = Servico_Completo.IdMServico ";
                    sql2 = sql2 + "INNER JOIN S_Servicos ON Servico_Completo.Servicos_Id = S_Servicos.Servicos_Id ";

                    sql2 = sql2 + "INNER JOIN S_Servicos_Tipo_Categ ON S_Servicos.Tipo_categ_id = S_Servicos_Tipo_Categ.Tipo_categ_id ";

                    sql2 = sql2 + "INNER JOIN Cidade ON S_Servicos.Cid_Id = Cidade.CID_id ";
                    sql2 = sql2 + "LEFT OUTER JOIN S_Mercado_Tarifa_Status ON S_Mercado_Tarifa_Status.S_mercado_tarifa_status_id = Monta_Servico_Valores.S_mercado_tarifa_status_id ";
                    sql2 = sql2 + "WHERE S_Servicos.Cid_Id = " + item.IdCidade;
                    sql2 = sql2 + " AND MServico_DataFrom <= '" + dataFrom.ToString("yyyyMMdd") + "' and MServico_DataTo >= '" + dataTo.ToString("yyyyMMdd") + "'";

                    if (Convert.ToInt32(ddlBaseTarifariaReportTarifario.SelectedValue) != 0)
                    {
                        sql2 = sql2 + "AND BaseTarifaria_id = " + Convert.ToInt32(ddlBaseTarifariaReportTarifario.SelectedValue);
                    }
                    if (Convert.ToInt32(ddlMercadoReportTarifario.SelectedValue) != 0)
                    {
                        sql2 = sql2 + "AND Mercado_id = " + Convert.ToInt32(ddlMercadoReportTarifario.SelectedValue);
                    }

                    if (!item.Sigla.Equals("RJ"))
                    {
                        sql2 = sql2 + " AND Supplier.Tarifario = 'True' ";
                    }

                    sql2 = sql2 + " AND SubServico is not null ";


                    ////////COMEÇA OR

                    sql2 = sql2 + " OR S_Servicos.Cid_Id = " + item.IdCidade;
                    sql2 = sql2 + " AND MServico_DataFrom <= '" + dataTo.ToString("yyyyMMdd") + "' and MServico_DataTo >= '" + dataFrom.ToString("yyyyMMdd") + "'";

                    if (Convert.ToInt32(ddlBaseTarifariaReportTarifario.SelectedValue) != 0)
                    {
                        sql2 = sql2 + "AND BaseTarifaria_id = " + Convert.ToInt32(ddlBaseTarifariaReportTarifario.SelectedValue);
                    }
                    if (Convert.ToInt32(ddlMercadoReportTarifario.SelectedValue) != 0)
                    {
                        sql2 = sql2 + "AND Mercado_id = " + Convert.ToInt32(ddlMercadoReportTarifario.SelectedValue);
                    }

                    if (!item.Sigla.Equals("RJ"))
                    {
                        sql2 = sql2 + " AND Supplier.Tarifario = 'True' ";
                    }

                    sql2 = sql2 + " AND SubServico is not null ";

                    sql2 = sql2 + "ORDER BY 'SIB', S_Servicos_Tipo_Categ.Ordenacao ";

                    SqlCommand cmd2 = new SqlCommand(sql2, Con);
                    SqlDataReader reader2 = cmd2.ExecuteReader();

                    listaServicos = new List<ModeloServico>();
                    cidade = "";

                    bool preenche = false;
                    while (reader2.Read())
                    {
                        cidade = reader2["CID_nome"].ToString();

                        servicos = new ModeloServico();
                        servicos.IdServico = reader2["Servicos_Id"].ToString();
                        servicos.IdSupplier = "";//reader2["S_id"].ToString();
                        listaServicos.Add(servicos);

                        preenche = true;
                    }

                    if (preenche)
                    {
                        drw = dt.NewRow();
                        drw["CServico"] = cidade;
                        dt.Rows.Add(drw);
                    }



                    foreach (ModeloServico item2 in listaServicos)
                    {



                        sql6 = "SELECT DISTINCT(Servico_Completo.SubServico) ";
                        sql6 = sql6 + "FROM Monta_Servico_Valores  ";
                        sql6 = sql6 + "INNER JOIN Monta_Servico ON Monta_Servico_Valores.IdMServico = Monta_Servico.IdMServico ";
                        sql6 = sql6 + "INNER JOIN S_Bases ON Monta_Servico_Valores.Base_id = S_Bases.Base_id ";
                        sql6 = sql6 + "INNER JOIN Servico_Completo ON Monta_Servico.IdMServico = Servico_Completo.IdMServico ";
                        sql6 = sql6 + "INNER JOIN S_Servicos ON Servico_Completo.Servicos_Id = S_Servicos.Servicos_Id ";
                        sql6 = sql6 + "WHERE S_Servicos.Servicos_Id = " + item2.IdServico;

                        SqlCommand cmd6 = new SqlCommand(sql6, Con);
                        SqlDataReader reader6 = cmd6.ExecuteReader();

                        bool subServico = false;
                        string txtSubServico = "";

                        while (reader6.Read())
                        {

                            txtSubServico = reader6["SubServico"].ToString();
                            if (!txtSubServico.Equals(""))
                            {
                                subServico = true;
                            }
                        }

                        if (!subServico)
                        {

                            sql3 = "SELECT DISTINCT(CAST(Base_de AS VARCHAR(5)) + '/' + CAST(Base_ate AS VARCHAR(5))) as Base, Base_ate, S_Servicos.Servicos_Nome, S_Servicos.SIB ";
                            sql3 = sql3 + "FROM S_Bases_Valor ";
                            sql3 = sql3 + "INNER JOIN Monta_Servico ON S_Bases_Valor.IdMServico = Monta_Servico.IdMServico ";
                            sql3 = sql3 + "INNER JOIN S_Bases ON S_Bases_Valor.Base_id = S_Bases.Base_id ";
                            sql3 = sql3 + "INNER JOIN Servico_Completo ON Monta_Servico.IdMServico = Servico_Completo.IdMServico_Temporada ";
                            sql3 = sql3 + "INNER JOIN S_Servicos ON Servico_Completo.Servicos_Id = S_Servicos.Servicos_Id ";
                            sql3 = sql3 + "INNER JOIN Cidade ON S_Servicos.Cid_Id = Cidade.CID_id ";
                            sql3 = sql3 + "WHERE S_Servicos.Servicos_Id = " + item2.IdServico;
                            sql3 = sql3 + " ORDER BY Base_ate ";
                        }
                        else
                        {

                            sql8 = "SELECT TOP(1) Monta_Servico.S_id ";
                            sql8 = sql8 + "FROM Monta_Servico_Valores  ";
                            sql8 = sql8 + "INNER JOIN Monta_Servico ON Monta_Servico_Valores.IdMServico = Monta_Servico.IdMServico ";
                            sql8 = sql8 + "INNER JOIN S_Bases ON Monta_Servico_Valores.Base_id = S_Bases.Base_id ";
                            sql8 = sql8 + "INNER JOIN Servico_Completo ON Monta_Servico.IdMServico = Servico_Completo.IdMServico ";
                            sql8 = sql8 + "INNER JOIN S_Servicos ON Servico_Completo.Servicos_Id = S_Servicos.Servicos_Id ";
                            sql8 = sql8 + "INNER JOIN Cidade ON S_Servicos.Cid_Id = Cidade.CID_id ";
                            sql8 = sql8 + "LEFT OUTER JOIN S_Mercado_Tarifa_Status ON S_Mercado_Tarifa_Status.S_mercado_tarifa_status_id = Monta_Servico_Valores.S_mercado_tarifa_status_id ";
                            sql8 = sql8 + "WHERE S_Servicos.Cid_Id = " + item.IdCidade;
                            sql8 = sql8 + " AND S_Servicos.Servicos_Id = " + item2.IdServico; ;
                            sql8 = sql8 + " ORDER BY S_id ";

                            SqlCommand cmd8 = new SqlCommand(sql8, Con);
                            SqlDataReader reader8 = cmd8.ExecuteReader();

                            while (reader8.Read())
                            {
                                item2.IdSupplier = reader8["S_id"].ToString();
                            }


                            sql3 = "SELECT DISTINCT(CAST(Base_de AS VARCHAR(5)) + '/' + CAST(Base_ate AS VARCHAR(5))) as Base, Base_ate, S_Servicos.Servicos_Nome, S_Servicos.SIB ";
                            sql3 = sql3 + "FROM Monta_Servico_Valores  ";
                            sql3 = sql3 + "INNER JOIN Monta_Servico ON Monta_Servico_Valores.IdMServico = Monta_Servico.IdMServico ";
                            sql3 = sql3 + "INNER JOIN S_Bases ON Monta_Servico_Valores.Base_id = S_Bases.Base_id ";
                            sql3 = sql3 + "INNER JOIN Servico_Completo ON Monta_Servico.IdMServico = Servico_Completo.IdMServico ";
                            sql3 = sql3 + "INNER JOIN S_Servicos ON Servico_Completo.Servicos_Id = S_Servicos.Servicos_Id ";
                            sql3 = sql3 + "INNER JOIN Cidade ON S_Servicos.Cid_Id = Cidade.CID_id ";
                            sql3 = sql3 + "LEFT OUTER JOIN S_Mercado_Tarifa_Status ON S_Mercado_Tarifa_Status.S_mercado_tarifa_status_id = Monta_Servico_Valores.S_mercado_tarifa_status_id ";
                            sql3 = sql3 + "WHERE S_Servicos.Servicos_Id = " + item2.IdServico;
                            sql3 = sql3 + "AND Monta_Servico.S_id = " + item2.IdSupplier;
                            sql3 = sql3 + " ORDER BY Base_ate ";
                        }


                        SqlCommand cmd3 = new SqlCommand(sql3, Con);
                        SqlDataReader reader3 = cmd3.ExecuteReader();

                        listaBases = new List<string>();
                        string servico = "";
                        string sibString = "";
                        idSupplier = item2.IdSupplier;

                        drw = dt.NewRow();

                        while (reader3.Read())
                        {
                            servico = reader3["Servicos_Nome"].ToString();
                            sibString = reader3["SIB"].ToString();
                            listaBases.Add(reader3["Base"].ToString());
                        }



                        if (cabecalho)
                        {
                            for (int i = 0; i < listaBases.Count; i++)
                            {
                                d = "C" + Convert.ToString(i + 1);
                                drw[d] = listaBases[i];
                            }

                            if (naoSib && (sibString.ToString().Equals("") || sibString.ToString().Equals("False")))
                            {
                                drw["Servico"] = "P R I V A T E   S E R V I C E S";
                                naoSib = false;
                            }

                            dt.Rows.Add(drw);

                            drw = dt.NewRow();

                            cabecalho = false;

                        }


                        if (sib && sibString.Equals("True"))
                        {
                            drw["Servico"] = "R E G U L A R   S E R V I C E S";
                            dt.Rows.Add(drw);
                            drw = dt.NewRow();
                            sib = false;
                        }

                        sql5 = "SELECT ";
                        if (!subServico)
                        {
                            sql5 = sql5 + "TOP(1) Monta_Servico.IdMServico AS IdServico, Monta_Servico.MServico_DataFrom ";
                        }
                        else
                        {
                            sql5 = sql5 + "DISTINCT(Monta_Servico.IdMServico) AS IdServico, Monta_Servico.MServico_DataFrom ";
                        }
                        sql5 = sql5 + "FROM Monta_Servico_Valores  ";
                        sql5 = sql5 + "INNER JOIN Monta_Servico ON Monta_Servico_Valores.IdMServico = Monta_Servico.IdMServico ";
                        sql5 = sql5 + "INNER JOIN S_Bases ON Monta_Servico_Valores.Base_id = S_Bases.Base_id ";
                        sql5 = sql5 + "INNER JOIN Servico_Completo ON Monta_Servico.IdMServico = Servico_Completo.IdMServico ";
                        sql5 = sql5 + "INNER JOIN S_Servicos ON Servico_Completo.Servicos_Id = S_Servicos.Servicos_Id ";
                        sql5 = sql5 + "INNER JOIN Cidade ON S_Servicos.Cid_Id = Cidade.CID_id ";
                        sql5 = sql5 + "LEFT OUTER JOIN S_Mercado_Tarifa_Status ON S_Mercado_Tarifa_Status.S_mercado_tarifa_status_id = Monta_Servico_Valores.S_mercado_tarifa_status_id ";

                        sql5 = sql5 + "WHERE S_Servicos.Servicos_Id = " + item2.IdServico;
                        if (subServico)
                        {
                            sql5 = sql5 + "AND Monta_Servico.S_id = " + idSupplier;
                        }

                        //alteração 22/10/2014 não aparecia sub serviços pois o TOP(1) da query sempre pegava o primeiro e não respeitava a data...

                        sql5 = sql5 + " AND (Monta_Servico.MServico_DataFrom <= '" + dataFrom.ToString("yyyyMMdd") + "') AND (Monta_Servico.MServico_DataTo >= '" + dataTo.ToString("yyyyMMdd") + "') OR";
                        sql5 = sql5 + " S_Servicos.Servicos_Id = " + item2.IdServico;
                        if (subServico)
                        {
                            sql5 = sql5 + "AND Monta_Servico.S_id = " + idSupplier;
                        }
                        sql5 = sql5 + " AND (Monta_Servico.MServico_DataFrom <= '" + dataTo.ToString("yyyyMMdd") + "') AND (Monta_Servico.MServico_DataTo >= '" + dataFrom.ToString("yyyyMMdd") + "') ";

                        //fim 22/10/2014

                        sql5 = sql5 + " ORDER BY Monta_Servico.MServico_DataFrom, IdServico ";

                        SqlCommand cmd5 = new SqlCommand(sql5, Con);
                        SqlDataReader reader5 = cmd5.ExecuteReader();

                        while (reader5.Read())
                        {

                            if (!subServico)
                            {

                                sql7 = "SELECT Cidade.CID_nome, Monta_Servico.MServico_DataFrom, Monta_Servico.MServico_DataTo, S_Servicos.Servicos_Nome, S_Bases.Base_de, S_Bases.Base_ate, S_Bases.Moeda_id, S_Bases_Valor.S_Bases_Valor_valor, '' as S_mercado_tarifa_status_nome, Moeda_id  ";
                                sql7 = sql7 + "FROM S_Bases_Valor ";
                                sql7 = sql7 + "INNER JOIN Monta_Servico ON S_Bases_Valor.IdMServico = Monta_Servico.IdMServico ";
                                sql7 = sql7 + "INNER JOIN S_Bases ON S_Bases_Valor.Base_id = S_Bases.Base_id ";
                                sql7 = sql7 + "INNER JOIN Servico_Completo ON Monta_Servico.IdMServico = Servico_Completo.IdMServico_Temporada ";
                                sql7 = sql7 + "INNER JOIN S_Servicos ON Servico_Completo.Servicos_Id = S_Servicos.Servicos_Id ";
                                sql7 = sql7 + "INNER JOIN Cidade ON S_Servicos.Cid_Id = Cidade.CID_id ";
                                sql7 = sql7 + "WHERE S_Servicos.Servicos_Id = " + item2.IdServico;
                                sql7 = sql7 + "AND Servico_Completo.IdMServico = " + reader5["IdServico"];

                                sql7 = sql7 + " AND MServico_DataFrom <= '" + dataFrom.ToString("yyyyMMdd") + "' and MServico_DataTo >= '" + dataTo.ToString("yyyyMMdd") + "'";

                                //////COMEÇAR OR

                                sql7 = sql7 + " OR S_Servicos.Servicos_Id = " + item2.IdServico;
                                sql7 = sql7 + " AND Servico_Completo.IdMServico = " + reader5["IdServico"];
                                sql7 = sql7 + " AND MServico_DataFrom <= '" + dataTo.ToString("yyyyMMdd") + "' and MServico_DataTo >= '" + dataFrom.ToString("yyyyMMdd") + "'";

                                sql7 = sql7 + " ORDER BY Cidade.CID_nome, S_Servicos.Servicos_Nome, S_Bases.Base_ate, S_Bases.Base_de, Monta_Servico.MServico_DataFrom ";



                                SqlCommand cmd7 = new SqlCommand(sql7, Con);
                                SqlDataReader reader7 = cmd7.ExecuteReader();

                                //bool passou = false;
                                int coluna = 1;
                                while (reader7.Read())
                                {
                                    cambio = 1;
                                    if (Convert.ToInt32(reader7["Moeda_id"]) != Convert.ToInt32(ddlCambioReportTarifario.SelectedValue) && !ddlCambioReportTarifario.SelectedValue.Equals("0"))
                                    {
                                        cambio = utils.CalcularCambio(Convert.ToInt32(reader7["Moeda_id"]), Convert.ToInt32(ddlCambioReportTarifario.SelectedValue));
                                    }

                                    adiciona = true;
                                    drw["Servico"] = servico;

                                    drw["D20"] = string.Format(new System.Globalization.CultureInfo("en-GB"), "{0:MMM, dd yyyy}", reader7["MServico_DataFrom"]) + " - " + string.Format(new System.Globalization.CultureInfo("en-GB"), "{0:MMM, dd yyyy}", reader7["MServico_DataTo"]);

                                    d = "D" + coluna.ToString();

                                    if (coluna < 19)
                                    {
                                        total = arrendodar(Convert.ToDecimal(NuloZero(reader7["S_Bases_Valor_valor"].ToString())) * cambio + ((Convert.ToDecimal(NuloZero(reader7["S_Bases_Valor_valor"].ToString())) * cambio) / 100) * markUp);
                                        totalString = Convert.ToString(total.ToString("N2"));
                                        drw[d] = totalString;
                                    }

                                    coluna = coluna + 1;

                                }

                            }
                            else
                            {
                                sql4 = "SELECT Cidade.CID_nome, Monta_Servico.MServico_DataFrom, Monta_Servico.MServico_DataTo, S_Servicos.Servicos_Nome, S_Bases.Base_de, S_Bases.Base_ate, S_Bases.Moeda_id, ";
                                sql4 = sql4 + "Monta_Servico_Valores.MServico_Valores_Bulk_Total, S_mercado_tarifa_status_nome, Servico_Completo.SubServico, Servico_Completo.IdMServico_Temporada ";
                                sql4 = sql4 + "FROM Monta_Servico_Valores  ";
                                sql4 = sql4 + "INNER JOIN Monta_Servico ON Monta_Servico_Valores.IdMServico = Monta_Servico.IdMServico ";
                                sql4 = sql4 + "INNER JOIN S_Bases ON Monta_Servico_Valores.Base_id = S_Bases.Base_id ";
                                sql4 = sql4 + "INNER JOIN Servico_Completo ON Monta_Servico.IdMServico = Servico_Completo.IdMServico ";
                                sql4 = sql4 + "INNER JOIN S_Servicos ON Servico_Completo.Servicos_Id = S_Servicos.Servicos_Id ";
                                sql4 = sql4 + "INNER JOIN Cidade ON S_Servicos.Cid_Id = Cidade.CID_id ";
                                sql4 = sql4 + "LEFT OUTER JOIN S_Mercado_Tarifa_Status ON S_Mercado_Tarifa_Status.S_mercado_tarifa_status_id = Monta_Servico_Valores.S_mercado_tarifa_status_id ";
                                sql4 = sql4 + "WHERE S_Servicos.Servicos_Id = " + item2.IdServico;
                                sql4 = sql4 + "AND Monta_Servico.IdMServico = " + reader5["IdServico"];

                                sql4 = sql4 + " AND MServico_DataFrom <= '" + dataFrom.ToString("yyyyMMdd") + "' and MServico_DataTo >= '" + dataTo.ToString("yyyyMMdd") + "'";


                                /////COMEÇA O OR

                                sql4 = sql4 + " OR S_Servicos.Servicos_Id = " + item2.IdServico;
                                sql4 = sql4 + " AND Monta_Servico.IdMServico = " + reader5["IdServico"];

                                sql4 = sql4 + " AND MServico_DataFrom <= '" + dataTo.ToString("yyyyMMdd") + "' and MServico_DataTo >= '" + dataFrom.ToString("yyyyMMdd") + "'";


                                sql4 = sql4 + " ORDER BY Cidade.CID_nome, S_Bases.Base_ate, S_Servicos.Servicos_Nome, S_Bases.Base_de, Monta_Servico.MServico_DataFrom ";



                                SqlCommand cmd4 = new SqlCommand(sql4, Con);
                                SqlDataReader reader4 = cmd4.ExecuteReader();

                                //bool passou = false;
                                int coluna = 1;
                                while (reader4.Read())
                                {


                                    if (reader4["MServico_Valores_Bulk_Total"].ToString().Equals(""))
                                    {
                                        totalString = reader4["S_mercado_tarifa_status_nome"].ToString();
                                    }
                                    else
                                    {
                                        cambio = 1;
                                        if (Convert.ToInt32(reader4["Moeda_id"]) != Convert.ToInt32(ddlCambioReportTarifario.SelectedValue) && !ddlCambioReportTarifario.SelectedValue.Equals("0"))
                                        {
                                            cambio = utils.CalcularCambio(Convert.ToInt32(reader4["Moeda_id"]), Convert.ToInt32(ddlCambioReportTarifario.SelectedValue));
                                        }


                                        total = arrendodar(Convert.ToDecimal(reader4["MServico_Valores_Bulk_Total"].ToString()) * cambio + ((Convert.ToDecimal(reader4["MServico_Valores_Bulk_Total"].ToString()) * cambio) / 100) * markUp);
                                        totalString = Convert.ToString(total.ToString("N2"));
                                    }

                                    adiciona = true;
                                    drw["Servico"] = servico;
                                    drw["D20"] = string.Format(new System.Globalization.CultureInfo("en-GB"), "{0:MMM, dd yyyy}", reader4["MServico_DataFrom"]) + " - " + string.Format(new System.Globalization.CultureInfo("en-GB"), "{0:MMM, dd yyyy}", reader4["MServico_DataTo"]);

                                    d = "D" + coluna.ToString();
                                    drw[d] = totalString;

                                    coluna = coluna + 1;

                                }
                            }

                            if (adiciona)
                            {
                                dt.Rows.Add(drw);
                                drw = dt.NewRow();
                                adiciona = false;
                            }

                        }

                    }
                }

                RptServicosTarifario rpt = new RptServicosTarifario();

                rpt.SetDataSource(dt);

                switch (ddlFormatoReportServicos.SelectedValue)
                {
                    case "1":
                        rpt.ExportToHttpResponse(
                            ExportFormatType.PortableDocFormat,
                            Response, true, "tarifarioservicos");
                        break;

                    case "2":
                        rpt.ExportToHttpResponse(
                            ExportFormatType.WordForWindows,
                            Response, true, "tarifarioservicos");
                        break;

                    case "3":
                        rpt.ExportToHttpResponse(
                            ExportFormatType.Excel,
                            Response, true, "tarifarioservicos");
                        break;
                }

                //rpt.ExportToHttpResponse(ExportFormatType.PortableDocFormat, Response, true, "tarifarioservicos");

            }
            catch (Exception ex)
            {

                MostrarMsg(ex.Message);
            }

        }

    }
}